From 760301bd57cc490a70c176bbdd468f465b66d613 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 9 Nov 2022 23:53:37 +0000 Subject: [PATCH 1/5] chore: Update to gapic-generator-python 1.6.0 feat(python): Add typing to proto.Message based class attributes feat(python): Snippetgen handling of repeated enum field PiperOrigin-RevId: 487326846 Source-Link: https://github.com/googleapis/googleapis/commit/da380c77bb87ba0f752baf07605dd1db30e1f7e1 Source-Link: https://github.com/googleapis/googleapis-gen/commit/61ef5762ee6731a0cbbfea22fd0eecee51ab1c8e Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNjFlZjU3NjJlZTY3MzFhMGNiYmZlYTIyZmQwZWVjZWU1MWFiMWM4ZSJ9 --- owl-bot-staging/v1alpha/.coveragerc | 17 + owl-bot-staging/v1alpha/.flake8 | 33 + owl-bot-staging/v1alpha/MANIFEST.in | 2 + owl-bot-staging/v1alpha/README.rst | 49 + owl-bot-staging/v1alpha/docs/conf.py | 376 ++ .../data_v1alpha/alpha_analytics_data.rst | 6 + .../v1alpha/docs/data_v1alpha/services.rst | 6 + .../v1alpha/docs/data_v1alpha/types.rst | 7 + owl-bot-staging/v1alpha/docs/index.rst | 7 + .../v1alpha/google/analytics/data/__init__.py | 157 + .../google/analytics/data/gapic_version.py | 16 + .../v1alpha/google/analytics/data/py.typed | 2 + .../google/analytics/data_v1alpha/__init__.py | 158 + .../data_v1alpha/gapic_metadata.json | 43 + .../google/analytics/data_v1alpha/py.typed | 2 + .../data_v1alpha/services/__init__.py | 15 + .../services/alpha_analytics_data/__init__.py | 22 + .../alpha_analytics_data/async_client.py | 294 ++ .../services/alpha_analytics_data/client.py | 492 +++ .../transports/__init__.py | 38 + .../alpha_analytics_data/transports/base.py | 155 + .../alpha_analytics_data/transports/grpc.py | 275 ++ .../transports/grpc_asyncio.py | 274 ++ .../alpha_analytics_data/transports/rest.py | 297 ++ .../analytics/data_v1alpha/types/__init__.py | 152 + .../data_v1alpha/types/analytics_data_api.py | 220 ++ .../analytics/data_v1alpha/types/data.py | 2404 ++++++++++++ owl-bot-staging/v1alpha/mypy.ini | 3 + owl-bot-staging/v1alpha/noxfile.py | 179 + ..._analytics_data_run_funnel_report_async.py | 51 + ...a_analytics_data_run_funnel_report_sync.py | 51 + ...etadata_google.analytics.data.v1alpha.json | 168 + .../scripts/fixup_data_v1alpha_keywords.py | 176 + owl-bot-staging/v1alpha/setup.py | 90 + .../v1alpha/testing/constraints-3.10.txt | 6 + .../v1alpha/testing/constraints-3.11.txt | 6 + .../v1alpha/testing/constraints-3.7.txt | 11 + .../v1alpha/testing/constraints-3.8.txt | 6 + .../v1alpha/testing/constraints-3.9.txt | 6 + owl-bot-staging/v1alpha/tests/__init__.py | 16 + .../v1alpha/tests/unit/__init__.py | 16 + .../v1alpha/tests/unit/gapic/__init__.py | 16 + .../tests/unit/gapic/data_v1alpha/__init__.py | 16 + .../data_v1alpha/test_alpha_analytics_data.py | 1455 ++++++++ owl-bot-staging/v1beta/.coveragerc | 17 + owl-bot-staging/v1beta/.flake8 | 33 + owl-bot-staging/v1beta/MANIFEST.in | 2 + owl-bot-staging/v1beta/README.rst | 49 + owl-bot-staging/v1beta/docs/conf.py | 376 ++ .../docs/data_v1beta/beta_analytics_data.rst | 6 + .../v1beta/docs/data_v1beta/services.rst | 6 + .../v1beta/docs/data_v1beta/types.rst | 7 + owl-bot-staging/v1beta/docs/index.rst | 7 + .../v1beta/google/analytics/data/__init__.py | 121 + .../google/analytics/data/gapic_version.py | 16 + .../v1beta/google/analytics/data/py.typed | 2 + .../google/analytics/data_v1beta/__init__.py | 122 + .../analytics/data_v1beta/gapic_metadata.json | 133 + .../google/analytics/data_v1beta/py.typed | 2 + .../data_v1beta/services/__init__.py | 15 + .../services/beta_analytics_data/__init__.py | 22 + .../beta_analytics_data/async_client.py | 846 +++++ .../services/beta_analytics_data/client.py | 1058 ++++++ .../transports/__init__.py | 38 + .../beta_analytics_data/transports/base.py | 239 ++ .../beta_analytics_data/transports/grpc.py | 467 +++ .../transports/grpc_asyncio.py | 466 +++ .../beta_analytics_data/transports/rest.py | 970 +++++ .../analytics/data_v1beta/types/__init__.py | 116 + .../data_v1beta/types/analytics_data_api.py | 978 +++++ .../analytics/data_v1beta/types/data.py | 1693 +++++++++ owl-bot-staging/v1beta/mypy.ini | 3 + owl-bot-staging/v1beta/noxfile.py | 179 + ...tics_data_batch_run_pivot_reports_async.py | 51 + ...ytics_data_batch_run_pivot_reports_sync.py | 51 + ..._analytics_data_batch_run_reports_async.py | 51 + ...a_analytics_data_batch_run_reports_sync.py | 51 + ...nalytics_data_check_compatibility_async.py | 51 + ...analytics_data_check_compatibility_sync.py | 51 + ..._beta_analytics_data_get_metadata_async.py | 52 + ...d_beta_analytics_data_get_metadata_sync.py | 52 + ...a_analytics_data_run_pivot_report_async.py | 51 + ...ta_analytics_data_run_pivot_report_sync.py | 51 + ...nalytics_data_run_realtime_report_async.py | 51 + ...analytics_data_run_realtime_report_sync.py | 51 + ...ed_beta_analytics_data_run_report_async.py | 51 + ...ted_beta_analytics_data_run_report_sync.py | 51 + ...metadata_google.analytics.data.v1beta.json | 1094 ++++++ .../scripts/fixup_data_v1beta_keywords.py | 182 + owl-bot-staging/v1beta/setup.py | 90 + .../v1beta/testing/constraints-3.10.txt | 6 + .../v1beta/testing/constraints-3.11.txt | 6 + .../v1beta/testing/constraints-3.7.txt | 11 + .../v1beta/testing/constraints-3.8.txt | 6 + .../v1beta/testing/constraints-3.9.txt | 6 + owl-bot-staging/v1beta/tests/__init__.py | 16 + owl-bot-staging/v1beta/tests/unit/__init__.py | 16 + .../v1beta/tests/unit/gapic/__init__.py | 16 + .../tests/unit/gapic/data_v1beta/__init__.py | 16 + .../data_v1beta/test_beta_analytics_data.py | 3230 +++++++++++++++++ 100 files changed, 21191 insertions(+) create mode 100644 owl-bot-staging/v1alpha/.coveragerc create mode 100644 owl-bot-staging/v1alpha/.flake8 create mode 100644 owl-bot-staging/v1alpha/MANIFEST.in create mode 100644 owl-bot-staging/v1alpha/README.rst create mode 100644 owl-bot-staging/v1alpha/docs/conf.py create mode 100644 owl-bot-staging/v1alpha/docs/data_v1alpha/alpha_analytics_data.rst create mode 100644 owl-bot-staging/v1alpha/docs/data_v1alpha/services.rst create mode 100644 owl-bot-staging/v1alpha/docs/data_v1alpha/types.rst create mode 100644 owl-bot-staging/v1alpha/docs/index.rst create mode 100644 owl-bot-staging/v1alpha/google/analytics/data/__init__.py create mode 100644 owl-bot-staging/v1alpha/google/analytics/data/gapic_version.py create mode 100644 owl-bot-staging/v1alpha/google/analytics/data/py.typed create mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/__init__.py create mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/gapic_metadata.json create mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/py.typed create mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/__init__.py create mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/__init__.py create mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/async_client.py create mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py create mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/__init__.py create mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/base.py create mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc.py create mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest.py create mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/__init__.py create mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/analytics_data_api.py create mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/data.py create mode 100644 owl-bot-staging/v1alpha/mypy.ini create mode 100644 owl-bot-staging/v1alpha/noxfile.py create mode 100644 owl-bot-staging/v1alpha/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_async.py create mode 100644 owl-bot-staging/v1alpha/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_sync.py create mode 100644 owl-bot-staging/v1alpha/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json create mode 100644 owl-bot-staging/v1alpha/scripts/fixup_data_v1alpha_keywords.py create mode 100644 owl-bot-staging/v1alpha/setup.py create mode 100644 owl-bot-staging/v1alpha/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/v1alpha/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/v1alpha/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/v1alpha/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/v1alpha/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/v1alpha/tests/__init__.py create mode 100644 owl-bot-staging/v1alpha/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1alpha/tests/unit/gapic/data_v1alpha/__init__.py create mode 100644 owl-bot-staging/v1alpha/tests/unit/gapic/data_v1alpha/test_alpha_analytics_data.py create mode 100644 owl-bot-staging/v1beta/.coveragerc create mode 100644 owl-bot-staging/v1beta/.flake8 create mode 100644 owl-bot-staging/v1beta/MANIFEST.in create mode 100644 owl-bot-staging/v1beta/README.rst create mode 100644 owl-bot-staging/v1beta/docs/conf.py create mode 100644 owl-bot-staging/v1beta/docs/data_v1beta/beta_analytics_data.rst create mode 100644 owl-bot-staging/v1beta/docs/data_v1beta/services.rst create mode 100644 owl-bot-staging/v1beta/docs/data_v1beta/types.rst create mode 100644 owl-bot-staging/v1beta/docs/index.rst create mode 100644 owl-bot-staging/v1beta/google/analytics/data/__init__.py create mode 100644 owl-bot-staging/v1beta/google/analytics/data/gapic_version.py create mode 100644 owl-bot-staging/v1beta/google/analytics/data/py.typed create mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/__init__.py create mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/py.typed create mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/services/__init__.py create mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/__init__.py create mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/async_client.py create mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/client.py create mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/__init__.py create mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/base.py create mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc.py create mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/rest.py create mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/types/__init__.py create mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/types/analytics_data_api.py create mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/types/data.py create mode 100644 owl-bot-staging/v1beta/mypy.ini create mode 100644 owl-bot-staging/v1beta/noxfile.py create mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_async.py create mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_sync.py create mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_async.py create mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_sync.py create mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_async.py create mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_sync.py create mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_async.py create mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_sync.py create mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_async.py create mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_sync.py create mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_async.py create mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_sync.py create mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_report_async.py create mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_report_sync.py create mode 100644 owl-bot-staging/v1beta/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json create mode 100644 owl-bot-staging/v1beta/scripts/fixup_data_v1beta_keywords.py create mode 100644 owl-bot-staging/v1beta/setup.py create mode 100644 owl-bot-staging/v1beta/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/v1beta/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/v1beta/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/v1beta/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/v1beta/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/v1beta/tests/__init__.py create mode 100644 owl-bot-staging/v1beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1beta/tests/unit/gapic/data_v1beta/__init__.py create mode 100644 owl-bot-staging/v1beta/tests/unit/gapic/data_v1beta/test_beta_analytics_data.py diff --git a/owl-bot-staging/v1alpha/.coveragerc b/owl-bot-staging/v1alpha/.coveragerc new file mode 100644 index 0000000..535122d --- /dev/null +++ b/owl-bot-staging/v1alpha/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/analytics/data/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1alpha/.flake8 b/owl-bot-staging/v1alpha/.flake8 new file mode 100644 index 0000000..29227d4 --- /dev/null +++ b/owl-bot-staging/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/v1alpha/MANIFEST.in b/owl-bot-staging/v1alpha/MANIFEST.in new file mode 100644 index 0000000..938f3f3 --- /dev/null +++ b/owl-bot-staging/v1alpha/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/analytics/data *.py +recursive-include google/analytics/data_v1alpha *.py diff --git a/owl-bot-staging/v1alpha/README.rst b/owl-bot-staging/v1alpha/README.rst new file mode 100644 index 0000000..d62497b --- /dev/null +++ b/owl-bot-staging/v1alpha/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Analytics Data 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 Data 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/v1alpha/docs/conf.py b/owl-bot-staging/v1alpha/docs/conf.py new file mode 100644 index 0000000..ad79bba --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-data 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-data" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google 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-data-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-data.tex", + u"google-analytics-data 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-data", + u"Google Analytics Data 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-data", + u"google-analytics-data Documentation", + author, + "google-analytics-data", + "GAPIC library for Google Analytics Data 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/v1alpha/docs/data_v1alpha/alpha_analytics_data.rst b/owl-bot-staging/v1alpha/docs/data_v1alpha/alpha_analytics_data.rst new file mode 100644 index 0000000..a59186b --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/data_v1alpha/alpha_analytics_data.rst @@ -0,0 +1,6 @@ +AlphaAnalyticsData +------------------------------------ + +.. automodule:: google.analytics.data_v1alpha.services.alpha_analytics_data + :members: + :inherited-members: diff --git a/owl-bot-staging/v1alpha/docs/data_v1alpha/services.rst b/owl-bot-staging/v1alpha/docs/data_v1alpha/services.rst new file mode 100644 index 0000000..607505d --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/data_v1alpha/services.rst @@ -0,0 +1,6 @@ +Services for Google Analytics Data v1alpha API +============================================== +.. toctree:: + :maxdepth: 2 + + alpha_analytics_data diff --git a/owl-bot-staging/v1alpha/docs/data_v1alpha/types.rst b/owl-bot-staging/v1alpha/docs/data_v1alpha/types.rst new file mode 100644 index 0000000..8498253 --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/data_v1alpha/types.rst @@ -0,0 +1,7 @@ +Types for Google Analytics Data v1alpha API +=========================================== + +.. automodule:: google.analytics.data_v1alpha.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1alpha/docs/index.rst b/owl-bot-staging/v1alpha/docs/index.rst new file mode 100644 index 0000000..1eb47c6 --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + data_v1alpha/services + data_v1alpha/types diff --git a/owl-bot-staging/v1alpha/google/analytics/data/__init__.py b/owl-bot-staging/v1alpha/google/analytics/data/__init__.py new file mode 100644 index 0000000..6902c35 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/analytics/data/__init__.py @@ -0,0 +1,157 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.data import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.analytics.data_v1alpha.services.alpha_analytics_data.client import AlphaAnalyticsDataClient +from google.analytics.data_v1alpha.services.alpha_analytics_data.async_client import AlphaAnalyticsDataAsyncClient + +from google.analytics.data_v1alpha.types.analytics_data_api import RunFunnelReportRequest +from google.analytics.data_v1alpha.types.analytics_data_api import RunFunnelReportResponse +from google.analytics.data_v1alpha.types.data import BetweenFilter +from google.analytics.data_v1alpha.types.data import DateRange +from google.analytics.data_v1alpha.types.data import Dimension +from google.analytics.data_v1alpha.types.data import DimensionExpression +from google.analytics.data_v1alpha.types.data import DimensionHeader +from google.analytics.data_v1alpha.types.data import DimensionValue +from google.analytics.data_v1alpha.types.data import EventSegment +from google.analytics.data_v1alpha.types.data import EventSegmentConditionGroup +from google.analytics.data_v1alpha.types.data import EventSegmentCriteria +from google.analytics.data_v1alpha.types.data import EventSegmentExclusion +from google.analytics.data_v1alpha.types.data import Filter +from google.analytics.data_v1alpha.types.data import FilterExpression +from google.analytics.data_v1alpha.types.data import FilterExpressionList +from google.analytics.data_v1alpha.types.data import Funnel +from google.analytics.data_v1alpha.types.data import FunnelBreakdown +from google.analytics.data_v1alpha.types.data import FunnelEventFilter +from google.analytics.data_v1alpha.types.data import FunnelFieldFilter +from google.analytics.data_v1alpha.types.data import FunnelFilterExpression +from google.analytics.data_v1alpha.types.data import FunnelFilterExpressionList +from google.analytics.data_v1alpha.types.data import FunnelNextAction +from google.analytics.data_v1alpha.types.data import FunnelParameterFilter +from google.analytics.data_v1alpha.types.data import FunnelParameterFilterExpression +from google.analytics.data_v1alpha.types.data import FunnelParameterFilterExpressionList +from google.analytics.data_v1alpha.types.data import FunnelResponseMetadata +from google.analytics.data_v1alpha.types.data import FunnelStep +from google.analytics.data_v1alpha.types.data import FunnelSubReport +from google.analytics.data_v1alpha.types.data import InListFilter +from google.analytics.data_v1alpha.types.data import MetricHeader +from google.analytics.data_v1alpha.types.data import MetricValue +from google.analytics.data_v1alpha.types.data import NumericFilter +from google.analytics.data_v1alpha.types.data import NumericValue +from google.analytics.data_v1alpha.types.data import PropertyQuota +from google.analytics.data_v1alpha.types.data import QuotaStatus +from google.analytics.data_v1alpha.types.data import Row +from google.analytics.data_v1alpha.types.data import SamplingMetadata +from google.analytics.data_v1alpha.types.data import Segment +from google.analytics.data_v1alpha.types.data import SegmentEventFilter +from google.analytics.data_v1alpha.types.data import SegmentFilter +from google.analytics.data_v1alpha.types.data import SegmentFilterExpression +from google.analytics.data_v1alpha.types.data import SegmentFilterExpressionList +from google.analytics.data_v1alpha.types.data import SegmentFilterScoping +from google.analytics.data_v1alpha.types.data import SegmentParameterFilter +from google.analytics.data_v1alpha.types.data import SegmentParameterFilterExpression +from google.analytics.data_v1alpha.types.data import SegmentParameterFilterExpressionList +from google.analytics.data_v1alpha.types.data import SegmentParameterFilterScoping +from google.analytics.data_v1alpha.types.data import SessionSegment +from google.analytics.data_v1alpha.types.data import SessionSegmentConditionGroup +from google.analytics.data_v1alpha.types.data import SessionSegmentCriteria +from google.analytics.data_v1alpha.types.data import SessionSegmentExclusion +from google.analytics.data_v1alpha.types.data import StringFilter +from google.analytics.data_v1alpha.types.data import UserSegment +from google.analytics.data_v1alpha.types.data import UserSegmentConditionGroup +from google.analytics.data_v1alpha.types.data import UserSegmentCriteria +from google.analytics.data_v1alpha.types.data import UserSegmentExclusion +from google.analytics.data_v1alpha.types.data import UserSegmentSequenceGroup +from google.analytics.data_v1alpha.types.data import UserSequenceStep +from google.analytics.data_v1alpha.types.data import EventCriteriaScoping +from google.analytics.data_v1alpha.types.data import EventExclusionDuration +from google.analytics.data_v1alpha.types.data import MetricType +from google.analytics.data_v1alpha.types.data import SessionCriteriaScoping +from google.analytics.data_v1alpha.types.data import SessionExclusionDuration +from google.analytics.data_v1alpha.types.data import UserCriteriaScoping +from google.analytics.data_v1alpha.types.data import UserExclusionDuration + +__all__ = ('AlphaAnalyticsDataClient', + 'AlphaAnalyticsDataAsyncClient', + 'RunFunnelReportRequest', + 'RunFunnelReportResponse', + 'BetweenFilter', + 'DateRange', + 'Dimension', + 'DimensionExpression', + 'DimensionHeader', + 'DimensionValue', + 'EventSegment', + 'EventSegmentConditionGroup', + 'EventSegmentCriteria', + 'EventSegmentExclusion', + 'Filter', + 'FilterExpression', + 'FilterExpressionList', + 'Funnel', + 'FunnelBreakdown', + 'FunnelEventFilter', + 'FunnelFieldFilter', + 'FunnelFilterExpression', + 'FunnelFilterExpressionList', + 'FunnelNextAction', + 'FunnelParameterFilter', + 'FunnelParameterFilterExpression', + 'FunnelParameterFilterExpressionList', + 'FunnelResponseMetadata', + 'FunnelStep', + 'FunnelSubReport', + 'InListFilter', + 'MetricHeader', + 'MetricValue', + 'NumericFilter', + 'NumericValue', + 'PropertyQuota', + 'QuotaStatus', + 'Row', + 'SamplingMetadata', + 'Segment', + 'SegmentEventFilter', + 'SegmentFilter', + 'SegmentFilterExpression', + 'SegmentFilterExpressionList', + 'SegmentFilterScoping', + 'SegmentParameterFilter', + 'SegmentParameterFilterExpression', + 'SegmentParameterFilterExpressionList', + 'SegmentParameterFilterScoping', + 'SessionSegment', + 'SessionSegmentConditionGroup', + 'SessionSegmentCriteria', + 'SessionSegmentExclusion', + 'StringFilter', + 'UserSegment', + 'UserSegmentConditionGroup', + 'UserSegmentCriteria', + 'UserSegmentExclusion', + 'UserSegmentSequenceGroup', + 'UserSequenceStep', + 'EventCriteriaScoping', + 'EventExclusionDuration', + 'MetricType', + 'SessionCriteriaScoping', + 'SessionExclusionDuration', + 'UserCriteriaScoping', + 'UserExclusionDuration', +) diff --git a/owl-bot-staging/v1alpha/google/analytics/data/gapic_version.py b/owl-bot-staging/v1alpha/google/analytics/data/gapic_version.py new file mode 100644 index 0000000..35859c3 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/analytics/data/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.1.0" diff --git a/owl-bot-staging/v1alpha/google/analytics/data/py.typed b/owl-bot-staging/v1alpha/google/analytics/data/py.typed new file mode 100644 index 0000000..1d549e5 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/analytics/data/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-analytics-data package uses inline types. diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/__init__.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/__init__.py new file mode 100644 index 0000000..a6fd5d7 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/__init__.py @@ -0,0 +1,158 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.data import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.alpha_analytics_data import AlphaAnalyticsDataClient +from .services.alpha_analytics_data import AlphaAnalyticsDataAsyncClient + +from .types.analytics_data_api import RunFunnelReportRequest +from .types.analytics_data_api import RunFunnelReportResponse +from .types.data import BetweenFilter +from .types.data import DateRange +from .types.data import Dimension +from .types.data import DimensionExpression +from .types.data import DimensionHeader +from .types.data import DimensionValue +from .types.data import EventSegment +from .types.data import EventSegmentConditionGroup +from .types.data import EventSegmentCriteria +from .types.data import EventSegmentExclusion +from .types.data import Filter +from .types.data import FilterExpression +from .types.data import FilterExpressionList +from .types.data import Funnel +from .types.data import FunnelBreakdown +from .types.data import FunnelEventFilter +from .types.data import FunnelFieldFilter +from .types.data import FunnelFilterExpression +from .types.data import FunnelFilterExpressionList +from .types.data import FunnelNextAction +from .types.data import FunnelParameterFilter +from .types.data import FunnelParameterFilterExpression +from .types.data import FunnelParameterFilterExpressionList +from .types.data import FunnelResponseMetadata +from .types.data import FunnelStep +from .types.data import FunnelSubReport +from .types.data import InListFilter +from .types.data import MetricHeader +from .types.data import MetricValue +from .types.data import NumericFilter +from .types.data import NumericValue +from .types.data import PropertyQuota +from .types.data import QuotaStatus +from .types.data import Row +from .types.data import SamplingMetadata +from .types.data import Segment +from .types.data import SegmentEventFilter +from .types.data import SegmentFilter +from .types.data import SegmentFilterExpression +from .types.data import SegmentFilterExpressionList +from .types.data import SegmentFilterScoping +from .types.data import SegmentParameterFilter +from .types.data import SegmentParameterFilterExpression +from .types.data import SegmentParameterFilterExpressionList +from .types.data import SegmentParameterFilterScoping +from .types.data import SessionSegment +from .types.data import SessionSegmentConditionGroup +from .types.data import SessionSegmentCriteria +from .types.data import SessionSegmentExclusion +from .types.data import StringFilter +from .types.data import UserSegment +from .types.data import UserSegmentConditionGroup +from .types.data import UserSegmentCriteria +from .types.data import UserSegmentExclusion +from .types.data import UserSegmentSequenceGroup +from .types.data import UserSequenceStep +from .types.data import EventCriteriaScoping +from .types.data import EventExclusionDuration +from .types.data import MetricType +from .types.data import SessionCriteriaScoping +from .types.data import SessionExclusionDuration +from .types.data import UserCriteriaScoping +from .types.data import UserExclusionDuration + +__all__ = ( + 'AlphaAnalyticsDataAsyncClient', +'AlphaAnalyticsDataClient', +'BetweenFilter', +'DateRange', +'Dimension', +'DimensionExpression', +'DimensionHeader', +'DimensionValue', +'EventCriteriaScoping', +'EventExclusionDuration', +'EventSegment', +'EventSegmentConditionGroup', +'EventSegmentCriteria', +'EventSegmentExclusion', +'Filter', +'FilterExpression', +'FilterExpressionList', +'Funnel', +'FunnelBreakdown', +'FunnelEventFilter', +'FunnelFieldFilter', +'FunnelFilterExpression', +'FunnelFilterExpressionList', +'FunnelNextAction', +'FunnelParameterFilter', +'FunnelParameterFilterExpression', +'FunnelParameterFilterExpressionList', +'FunnelResponseMetadata', +'FunnelStep', +'FunnelSubReport', +'InListFilter', +'MetricHeader', +'MetricType', +'MetricValue', +'NumericFilter', +'NumericValue', +'PropertyQuota', +'QuotaStatus', +'Row', +'RunFunnelReportRequest', +'RunFunnelReportResponse', +'SamplingMetadata', +'Segment', +'SegmentEventFilter', +'SegmentFilter', +'SegmentFilterExpression', +'SegmentFilterExpressionList', +'SegmentFilterScoping', +'SegmentParameterFilter', +'SegmentParameterFilterExpression', +'SegmentParameterFilterExpressionList', +'SegmentParameterFilterScoping', +'SessionCriteriaScoping', +'SessionExclusionDuration', +'SessionSegment', +'SessionSegmentConditionGroup', +'SessionSegmentCriteria', +'SessionSegmentExclusion', +'StringFilter', +'UserCriteriaScoping', +'UserExclusionDuration', +'UserSegment', +'UserSegmentConditionGroup', +'UserSegmentCriteria', +'UserSegmentExclusion', +'UserSegmentSequenceGroup', +'UserSequenceStep', +) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/gapic_metadata.json b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/gapic_metadata.json new file mode 100644 index 0000000..f8812c5 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/gapic_metadata.json @@ -0,0 +1,43 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.analytics.data_v1alpha", + "protoPackage": "google.analytics.data.v1alpha", + "schema": "1.0", + "services": { + "AlphaAnalyticsData": { + "clients": { + "grpc": { + "libraryClient": "AlphaAnalyticsDataClient", + "rpcs": { + "RunFunnelReport": { + "methods": [ + "run_funnel_report" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AlphaAnalyticsDataAsyncClient", + "rpcs": { + "RunFunnelReport": { + "methods": [ + "run_funnel_report" + ] + } + } + }, + "rest": { + "libraryClient": "AlphaAnalyticsDataClient", + "rpcs": { + "RunFunnelReport": { + "methods": [ + "run_funnel_report" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/py.typed b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/py.typed new file mode 100644 index 0000000..1d549e5 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-analytics-data package uses inline types. diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/__init__.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/__init__.py new file mode 100644 index 0000000..e8e1c38 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/__init__.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/__init__.py new file mode 100644 index 0000000..8948d2f --- /dev/null +++ b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 AlphaAnalyticsDataClient +from .async_client import AlphaAnalyticsDataAsyncClient + +__all__ = ( + 'AlphaAnalyticsDataClient', + 'AlphaAnalyticsDataAsyncClient', +) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/async_client.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/async_client.py new file mode 100644 index 0000000..a8eaaaf --- /dev/null +++ b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/async_client.py @@ -0,0 +1,294 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.analytics.data_v1alpha.types import analytics_data_api +from google.analytics.data_v1alpha.types import data +from .transports.base import AlphaAnalyticsDataTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AlphaAnalyticsDataGrpcAsyncIOTransport +from .client import AlphaAnalyticsDataClient + + +class AlphaAnalyticsDataAsyncClient: + """Google Analytics reporting data service.""" + + _client: AlphaAnalyticsDataClient + + DEFAULT_ENDPOINT = AlphaAnalyticsDataClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AlphaAnalyticsDataClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(AlphaAnalyticsDataClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AlphaAnalyticsDataClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AlphaAnalyticsDataClient.common_folder_path) + parse_common_folder_path = staticmethod(AlphaAnalyticsDataClient.parse_common_folder_path) + common_organization_path = staticmethod(AlphaAnalyticsDataClient.common_organization_path) + parse_common_organization_path = staticmethod(AlphaAnalyticsDataClient.parse_common_organization_path) + common_project_path = staticmethod(AlphaAnalyticsDataClient.common_project_path) + parse_common_project_path = staticmethod(AlphaAnalyticsDataClient.parse_common_project_path) + common_location_path = staticmethod(AlphaAnalyticsDataClient.common_location_path) + parse_common_location_path = staticmethod(AlphaAnalyticsDataClient.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: + AlphaAnalyticsDataAsyncClient: The constructed client. + """ + return AlphaAnalyticsDataClient.from_service_account_info.__func__(AlphaAnalyticsDataAsyncClient, 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: + AlphaAnalyticsDataAsyncClient: The constructed client. + """ + return AlphaAnalyticsDataClient.from_service_account_file.__func__(AlphaAnalyticsDataAsyncClient, 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 variabel 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 AlphaAnalyticsDataClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AlphaAnalyticsDataTransport: + """Returns the transport used by the client instance. + + Returns: + AlphaAnalyticsDataTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(AlphaAnalyticsDataClient).get_transport_class, type(AlphaAnalyticsDataClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AlphaAnalyticsDataTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the alpha analytics data client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.AlphaAnalyticsDataTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = AlphaAnalyticsDataClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def run_funnel_report(self, + request: Optional[Union[analytics_data_api.RunFunnelReportRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.RunFunnelReportResponse: + r"""Returns a customized funnel report of your Google Analytics + event data. The data returned from the API is as a table with + columns for the requested dimensions and metrics. + + Funnel exploration lets you visualize the steps your users take + to complete a task and quickly see how well they are succeeding + or failing at each step. For example, how do prospects become + shoppers and then become buyers? How do one time buyers become + repeat buyers? With this information, you can improve + inefficient or abandoned customer journeys. To learn more, see + `GA4 Funnel + Explorations `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 data_v1alpha + + async def sample_run_funnel_report(): + # Create a client + client = data_v1alpha.AlphaAnalyticsDataAsyncClient() + + # Initialize request argument(s) + request = data_v1alpha.RunFunnelReportRequest( + ) + + # Make the request + response = await client.run_funnel_report(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.data_v1alpha.types.RunFunnelReportRequest, dict]]): + The request object. The request for a funnel 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.data_v1alpha.types.RunFunnelReportResponse: + The funnel report response contains + two sub reports. The two sub reports are + different combinations of dimensions and + metrics. + + """ + # Create or coerce a protobuf request object. + request = analytics_data_api.RunFunnelReportRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.run_funnel_report, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("property", request.property), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-analytics-data", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AlphaAnalyticsDataAsyncClient", +) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py new file mode 100644 index 0000000..a135a8a --- /dev/null +++ b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py @@ -0,0 +1,492 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.analytics.data_v1alpha.types import analytics_data_api +from google.analytics.data_v1alpha.types import data +from .transports.base import AlphaAnalyticsDataTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AlphaAnalyticsDataGrpcTransport +from .transports.grpc_asyncio import AlphaAnalyticsDataGrpcAsyncIOTransport +from .transports.rest import AlphaAnalyticsDataRestTransport + + +class AlphaAnalyticsDataClientMeta(type): + """Metaclass for the AlphaAnalyticsData 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[AlphaAnalyticsDataTransport]] + _transport_registry["grpc"] = AlphaAnalyticsDataGrpcTransport + _transport_registry["grpc_asyncio"] = AlphaAnalyticsDataGrpcAsyncIOTransport + _transport_registry["rest"] = AlphaAnalyticsDataRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AlphaAnalyticsDataTransport]: + """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 AlphaAnalyticsDataClient(metaclass=AlphaAnalyticsDataClientMeta): + """Google Analytics reporting data service.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "analyticsdata.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AlphaAnalyticsDataClient: 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: + AlphaAnalyticsDataClient: 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) -> AlphaAnalyticsDataTransport: + """Returns the transport used by the client instance. + + Returns: + AlphaAnalyticsDataTransport: The transport used by the client + instance. + """ + return self._transport + + @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): + """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 variabel 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. + """ + 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 + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AlphaAnalyticsDataTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the alpha analytics data client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, AlphaAnalyticsDataTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(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. + if isinstance(transport, AlphaAnalyticsDataTransport): + # transport is a AlphaAnalyticsDataTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def run_funnel_report(self, + request: Optional[Union[analytics_data_api.RunFunnelReportRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.RunFunnelReportResponse: + r"""Returns a customized funnel report of your Google Analytics + event data. The data returned from the API is as a table with + columns for the requested dimensions and metrics. + + Funnel exploration lets you visualize the steps your users take + to complete a task and quickly see how well they are succeeding + or failing at each step. For example, how do prospects become + shoppers and then become buyers? How do one time buyers become + repeat buyers? With this information, you can improve + inefficient or abandoned customer journeys. To learn more, see + `GA4 Funnel + Explorations `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 data_v1alpha + + def sample_run_funnel_report(): + # Create a client + client = data_v1alpha.AlphaAnalyticsDataClient() + + # Initialize request argument(s) + request = data_v1alpha.RunFunnelReportRequest( + ) + + # Make the request + response = client.run_funnel_report(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.data_v1alpha.types.RunFunnelReportRequest, dict]): + The request object. The request for a funnel 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.data_v1alpha.types.RunFunnelReportResponse: + The funnel report response contains + two sub reports. The two sub reports are + different combinations of dimensions and + metrics. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a analytics_data_api.RunFunnelReportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, analytics_data_api.RunFunnelReportRequest): + request = analytics_data_api.RunFunnelReportRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.run_funnel_report] + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-analytics-data", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AlphaAnalyticsDataClient", +) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/__init__.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/__init__.py new file mode 100644 index 0000000..45c2709 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 AlphaAnalyticsDataTransport +from .grpc import AlphaAnalyticsDataGrpcTransport +from .grpc_asyncio import AlphaAnalyticsDataGrpcAsyncIOTransport +from .rest import AlphaAnalyticsDataRestTransport +from .rest import AlphaAnalyticsDataRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AlphaAnalyticsDataTransport]] +_transport_registry['grpc'] = AlphaAnalyticsDataGrpcTransport +_transport_registry['grpc_asyncio'] = AlphaAnalyticsDataGrpcAsyncIOTransport +_transport_registry['rest'] = AlphaAnalyticsDataRestTransport + +__all__ = ( + 'AlphaAnalyticsDataTransport', + 'AlphaAnalyticsDataGrpcTransport', + 'AlphaAnalyticsDataGrpcAsyncIOTransport', + 'AlphaAnalyticsDataRestTransport', + 'AlphaAnalyticsDataRestInterceptor', +) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/base.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/base.py new file mode 100644 index 0000000..0b338c5 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/base.py @@ -0,0 +1,155 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.analytics.data_v1alpha.types import analytics_data_api + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-analytics-data', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class AlphaAnalyticsDataTransport(abc.ABC): + """Abstract transport class for AlphaAnalyticsData.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/analytics', + 'https://www.googleapis.com/auth/analytics.readonly', + ) + + DEFAULT_HOST: str = 'analyticsdata.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. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.run_funnel_report: gapic_v1.method.wrap_method( + self.run_funnel_report, + default_timeout=60.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def run_funnel_report(self) -> Callable[ + [analytics_data_api.RunFunnelReportRequest], + Union[ + analytics_data_api.RunFunnelReportResponse, + Awaitable[analytics_data_api.RunFunnelReportResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AlphaAnalyticsDataTransport', +) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc.py new file mode 100644 index 0000000..1f2de5b --- /dev/null +++ b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc.py @@ -0,0 +1,275 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.data_v1alpha.types import analytics_data_api +from .base import AlphaAnalyticsDataTransport, DEFAULT_CLIENT_INFO + + +class AlphaAnalyticsDataGrpcTransport(AlphaAnalyticsDataTransport): + """gRPC backend transport for AlphaAnalyticsData. + + Google Analytics reporting data service. + + 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 = 'analyticsdata.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'analyticsdata.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 run_funnel_report(self) -> Callable[ + [analytics_data_api.RunFunnelReportRequest], + analytics_data_api.RunFunnelReportResponse]: + r"""Return a callable for the run funnel report method over gRPC. + + Returns a customized funnel report of your Google Analytics + event data. The data returned from the API is as a table with + columns for the requested dimensions and metrics. + + Funnel exploration lets you visualize the steps your users take + to complete a task and quickly see how well they are succeeding + or failing at each step. For example, how do prospects become + shoppers and then become buyers? How do one time buyers become + repeat buyers? With this information, you can improve + inefficient or abandoned customer journeys. To learn more, see + `GA4 Funnel + Explorations `__. + + Returns: + Callable[[~.RunFunnelReportRequest], + ~.RunFunnelReportResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_funnel_report' not in self._stubs: + self._stubs['run_funnel_report'] = self.grpc_channel.unary_unary( + '/google.analytics.data.v1alpha.AlphaAnalyticsData/RunFunnelReport', + request_serializer=analytics_data_api.RunFunnelReportRequest.serialize, + response_deserializer=analytics_data_api.RunFunnelReportResponse.deserialize, + ) + return self._stubs['run_funnel_report'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AlphaAnalyticsDataGrpcTransport', +) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py new file mode 100644 index 0000000..b9a934e --- /dev/null +++ b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py @@ -0,0 +1,274 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.analytics.data_v1alpha.types import analytics_data_api +from .base import AlphaAnalyticsDataTransport, DEFAULT_CLIENT_INFO +from .grpc import AlphaAnalyticsDataGrpcTransport + + +class AlphaAnalyticsDataGrpcAsyncIOTransport(AlphaAnalyticsDataTransport): + """gRPC AsyncIO backend transport for AlphaAnalyticsData. + + Google Analytics reporting data service. + + 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 = 'analyticsdata.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'analyticsdata.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def run_funnel_report(self) -> Callable[ + [analytics_data_api.RunFunnelReportRequest], + Awaitable[analytics_data_api.RunFunnelReportResponse]]: + r"""Return a callable for the run funnel report method over gRPC. + + Returns a customized funnel report of your Google Analytics + event data. The data returned from the API is as a table with + columns for the requested dimensions and metrics. + + Funnel exploration lets you visualize the steps your users take + to complete a task and quickly see how well they are succeeding + or failing at each step. For example, how do prospects become + shoppers and then become buyers? How do one time buyers become + repeat buyers? With this information, you can improve + inefficient or abandoned customer journeys. To learn more, see + `GA4 Funnel + Explorations `__. + + Returns: + Callable[[~.RunFunnelReportRequest], + Awaitable[~.RunFunnelReportResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_funnel_report' not in self._stubs: + self._stubs['run_funnel_report'] = self.grpc_channel.unary_unary( + '/google.analytics.data.v1alpha.AlphaAnalyticsData/RunFunnelReport', + request_serializer=analytics_data_api.RunFunnelReportRequest.serialize, + response_deserializer=analytics_data_api.RunFunnelReportResponse.deserialize, + ) + return self._stubs['run_funnel_report'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'AlphaAnalyticsDataGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest.py new file mode 100644 index 0000000..6356b25 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest.py @@ -0,0 +1,297 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.analytics.data_v1alpha.types import analytics_data_api + +from .base import AlphaAnalyticsDataTransport, 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 AlphaAnalyticsDataRestInterceptor: + """Interceptor for AlphaAnalyticsData. + + 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 AlphaAnalyticsDataRestTransport. + + .. code-block:: python + class MyCustomAlphaAnalyticsDataInterceptor(AlphaAnalyticsDataRestInterceptor): + def pre_run_funnel_report(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_run_funnel_report(response): + logging.log(f"Received response: {response}") + + transport = AlphaAnalyticsDataRestTransport(interceptor=MyCustomAlphaAnalyticsDataInterceptor()) + client = AlphaAnalyticsDataClient(transport=transport) + + + """ + def pre_run_funnel_report(self, request: analytics_data_api.RunFunnelReportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_data_api.RunFunnelReportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for run_funnel_report + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlphaAnalyticsData server. + """ + return request, metadata + + def post_run_funnel_report(self, response: analytics_data_api.RunFunnelReportResponse) -> analytics_data_api.RunFunnelReportResponse: + """Post-rpc interceptor for run_funnel_report + + Override in a subclass to manipulate the response + after it is returned by the AlphaAnalyticsData server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AlphaAnalyticsDataRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AlphaAnalyticsDataRestInterceptor + + +class AlphaAnalyticsDataRestTransport(AlphaAnalyticsDataTransport): + """REST backend transport for AlphaAnalyticsData. + + Google Analytics reporting data service. + + 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 + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via an issue in this + library's source repository. Thank you! + """ + + def __init__(self, *, + host: str = 'analyticsdata.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[AlphaAnalyticsDataRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is 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 AlphaAnalyticsDataRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _RunFunnelReport(AlphaAnalyticsDataRestStub): + def __hash__(self): + return hash("RunFunnelReport") + + def __call__(self, + request: analytics_data_api.RunFunnelReportRequest, *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.RunFunnelReportResponse: + r"""Call the run funnel report method over HTTP. + + Args: + request (~.analytics_data_api.RunFunnelReportRequest): + The request object. The request for a funnel 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_data_api.RunFunnelReportResponse: + The funnel report response contains + two sub reports. The two sub reports are + different combinations of dimensions and + metrics. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{property=properties/*}:runFunnelReport', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_run_funnel_report(request, metadata) + pb_request = analytics_data_api.RunFunnelReportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=False + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=False, + )) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._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_data_api.RunFunnelReportResponse() + pb_resp = analytics_data_api.RunFunnelReportResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_run_funnel_report(resp) + return resp + + @property + def run_funnel_report(self) -> Callable[ + [analytics_data_api.RunFunnelReportRequest], + analytics_data_api.RunFunnelReportResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RunFunnelReport(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AlphaAnalyticsDataRestTransport', +) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/__init__.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/__init__.py new file mode 100644 index 0000000..0634c97 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/__init__.py @@ -0,0 +1,152 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .analytics_data_api import ( + RunFunnelReportRequest, + RunFunnelReportResponse, +) +from .data import ( + BetweenFilter, + DateRange, + Dimension, + DimensionExpression, + DimensionHeader, + DimensionValue, + EventSegment, + EventSegmentConditionGroup, + EventSegmentCriteria, + EventSegmentExclusion, + Filter, + FilterExpression, + FilterExpressionList, + Funnel, + FunnelBreakdown, + FunnelEventFilter, + FunnelFieldFilter, + FunnelFilterExpression, + FunnelFilterExpressionList, + FunnelNextAction, + FunnelParameterFilter, + FunnelParameterFilterExpression, + FunnelParameterFilterExpressionList, + FunnelResponseMetadata, + FunnelStep, + FunnelSubReport, + InListFilter, + MetricHeader, + MetricValue, + NumericFilter, + NumericValue, + PropertyQuota, + QuotaStatus, + Row, + SamplingMetadata, + Segment, + SegmentEventFilter, + SegmentFilter, + SegmentFilterExpression, + SegmentFilterExpressionList, + SegmentFilterScoping, + SegmentParameterFilter, + SegmentParameterFilterExpression, + SegmentParameterFilterExpressionList, + SegmentParameterFilterScoping, + SessionSegment, + SessionSegmentConditionGroup, + SessionSegmentCriteria, + SessionSegmentExclusion, + StringFilter, + UserSegment, + UserSegmentConditionGroup, + UserSegmentCriteria, + UserSegmentExclusion, + UserSegmentSequenceGroup, + UserSequenceStep, + EventCriteriaScoping, + EventExclusionDuration, + MetricType, + SessionCriteriaScoping, + SessionExclusionDuration, + UserCriteriaScoping, + UserExclusionDuration, +) + +__all__ = ( + 'RunFunnelReportRequest', + 'RunFunnelReportResponse', + 'BetweenFilter', + 'DateRange', + 'Dimension', + 'DimensionExpression', + 'DimensionHeader', + 'DimensionValue', + 'EventSegment', + 'EventSegmentConditionGroup', + 'EventSegmentCriteria', + 'EventSegmentExclusion', + 'Filter', + 'FilterExpression', + 'FilterExpressionList', + 'Funnel', + 'FunnelBreakdown', + 'FunnelEventFilter', + 'FunnelFieldFilter', + 'FunnelFilterExpression', + 'FunnelFilterExpressionList', + 'FunnelNextAction', + 'FunnelParameterFilter', + 'FunnelParameterFilterExpression', + 'FunnelParameterFilterExpressionList', + 'FunnelResponseMetadata', + 'FunnelStep', + 'FunnelSubReport', + 'InListFilter', + 'MetricHeader', + 'MetricValue', + 'NumericFilter', + 'NumericValue', + 'PropertyQuota', + 'QuotaStatus', + 'Row', + 'SamplingMetadata', + 'Segment', + 'SegmentEventFilter', + 'SegmentFilter', + 'SegmentFilterExpression', + 'SegmentFilterExpressionList', + 'SegmentFilterScoping', + 'SegmentParameterFilter', + 'SegmentParameterFilterExpression', + 'SegmentParameterFilterExpressionList', + 'SegmentParameterFilterScoping', + 'SessionSegment', + 'SessionSegmentConditionGroup', + 'SessionSegmentCriteria', + 'SessionSegmentExclusion', + 'StringFilter', + 'UserSegment', + 'UserSegmentConditionGroup', + 'UserSegmentCriteria', + 'UserSegmentExclusion', + 'UserSegmentSequenceGroup', + 'UserSequenceStep', + 'EventCriteriaScoping', + 'EventExclusionDuration', + 'MetricType', + 'SessionCriteriaScoping', + 'SessionExclusionDuration', + 'UserCriteriaScoping', + 'UserExclusionDuration', +) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/analytics_data_api.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/analytics_data_api.py new file mode 100644 index 0000000..776fbf7 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/analytics_data_api.py @@ -0,0 +1,220 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.analytics.data_v1alpha.types import data + + +__protobuf__ = proto.module( + package='google.analytics.data.v1alpha', + manifest={ + 'RunFunnelReportRequest', + 'RunFunnelReportResponse', + }, +) + + +class RunFunnelReportRequest(proto.Message): + r"""The request for a funnel report. + + Attributes: + property (str): + A Google Analytics GA4 property identifier whose events are + tracked. Specified in the URL path and not the body. To + learn more, see `where to find your Property + ID `__. + Within a batch request, this property should either be + unspecified or consistent with the batch-level property. + + Example: properties/1234 + date_ranges (MutableSequence[google.analytics.data_v1alpha.types.DateRange]): + Date ranges of data 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 event data for the + overlapping days is included in the response + rows for both date ranges. + funnel (google.analytics.data_v1alpha.types.Funnel): + The configuration of this request's funnel. + This funnel configuration is required. + funnel_breakdown (google.analytics.data_v1alpha.types.FunnelBreakdown): + If specified, this breakdown adds a dimension to the funnel + table sub report response. This breakdown dimension expands + each funnel step to the unique values of the breakdown + dimension. For example, a breakdown by the + ``deviceCategory`` dimension will create rows for + ``mobile``, ``tablet``, ``desktop``, and the total. + funnel_next_action (google.analytics.data_v1alpha.types.FunnelNextAction): + If specified, next action adds a dimension to the funnel + visualization sub report response. This next action + dimension expands each funnel step to the unique values of + the next action. For example a next action of the + ``eventName`` dimension will create rows for several events + (i.e. ``session_start`` & ``click``) and the total. + + Next action only supports ``eventName`` and most Page / + Screen dimensions like ``pageTitle`` and ``pagePath``. + funnel_visualization_type (google.analytics.data_v1alpha.types.RunFunnelReportRequest.FunnelVisualizationType): + The funnel visualization type controls the dimensions + present in the funnel visualization sub report response. If + not specified, ``STANDARD_FUNNEL`` is used. + segments (MutableSequence[google.analytics.data_v1alpha.types.Segment]): + The configurations of segments. Segments are + subsets of a property's data. In a funnel report + with segments, the funnel is evaluated in each + segment. + Each segment specified in this request + produces a separate row in the response; in the + response, each segment identified by its name. + + The segments parameter is optional. Requests are + limited to 4 segments. + 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 can also return fewer rows than the requested + ``limit``, if there aren't as many dimension values as the + ``limit``. + dimension_filter (google.analytics.data_v1alpha.types.FilterExpression): + Dimension filters allow you to ask for only specific + dimension values in the report. To learn more, see `Creating + a Report: Dimension + Filters `__ + for examples. Metrics cannot be used in this filter. + return_property_quota (bool): + Toggles whether to return the current state of this + Analytics Property's quota. Quota is returned in + `PropertyQuota <#PropertyQuota>`__. + """ + class FunnelVisualizationType(proto.Enum): + r"""Controls the dimensions present in the funnel visualization + sub report response. + """ + FUNNEL_VISUALIZATION_TYPE_UNSPECIFIED = 0 + STANDARD_FUNNEL = 1 + TRENDED_FUNNEL = 2 + + property: str = proto.Field( + proto.STRING, + number=1, + ) + date_ranges: MutableSequence[data.DateRange] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=data.DateRange, + ) + funnel: data.Funnel = proto.Field( + proto.MESSAGE, + number=3, + message=data.Funnel, + ) + funnel_breakdown: data.FunnelBreakdown = proto.Field( + proto.MESSAGE, + number=4, + message=data.FunnelBreakdown, + ) + funnel_next_action: data.FunnelNextAction = proto.Field( + proto.MESSAGE, + number=5, + message=data.FunnelNextAction, + ) + funnel_visualization_type: FunnelVisualizationType = proto.Field( + proto.ENUM, + number=6, + enum=FunnelVisualizationType, + ) + segments: MutableSequence[data.Segment] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=data.Segment, + ) + limit: int = proto.Field( + proto.INT64, + number=9, + ) + dimension_filter: data.FilterExpression = proto.Field( + proto.MESSAGE, + number=10, + message=data.FilterExpression, + ) + return_property_quota: bool = proto.Field( + proto.BOOL, + number=12, + ) + + +class RunFunnelReportResponse(proto.Message): + r"""The funnel report response contains two sub reports. The two + sub reports are different combinations of dimensions and + metrics. + + Attributes: + funnel_table (google.analytics.data_v1alpha.types.FunnelSubReport): + The funnel table is a report with the funnel + step, segment, breakdown dimension, active + users, completion rate, abandonments, and + abandonments rate. + + The segment dimension is only present in this + response if a segment was requested. The + breakdown dimension is only present in this + response if it was requested. + funnel_visualization (google.analytics.data_v1alpha.types.FunnelSubReport): + The funnel visualization is a report with the funnel step, + segment, date, next action dimension, and active users. + + The segment dimension is only present in this response if a + segment was requested. The date dimension is only present in + this response if it was requested via the ``TRENDED_FUNNEL`` + funnel type. The next action dimension is only present in + the response if it was requested. + property_quota (google.analytics.data_v1alpha.types.PropertyQuota): + This Analytics Property's quota state + including this request. + kind (str): + Identifies what kind of resource this message is. This + ``kind`` is always the fixed string + "analyticsData#runFunnelReport". Useful to distinguish + between response types in JSON. + """ + + funnel_table: data.FunnelSubReport = proto.Field( + proto.MESSAGE, + number=1, + message=data.FunnelSubReport, + ) + funnel_visualization: data.FunnelSubReport = proto.Field( + proto.MESSAGE, + number=2, + message=data.FunnelSubReport, + ) + property_quota: data.PropertyQuota = proto.Field( + proto.MESSAGE, + number=3, + message=data.PropertyQuota, + ) + kind: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/data.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/data.py new file mode 100644 index 0000000..f16beae --- /dev/null +++ b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/data.py @@ -0,0 +1,2404 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.analytics.data.v1alpha', + manifest={ + 'UserCriteriaScoping', + 'UserExclusionDuration', + 'SessionCriteriaScoping', + 'SessionExclusionDuration', + 'EventCriteriaScoping', + 'EventExclusionDuration', + 'MetricType', + 'DateRange', + 'Dimension', + 'DimensionExpression', + 'FilterExpression', + 'FilterExpressionList', + 'Filter', + 'StringFilter', + 'InListFilter', + 'NumericFilter', + 'BetweenFilter', + 'NumericValue', + 'DimensionHeader', + 'MetricHeader', + 'Row', + 'DimensionValue', + 'MetricValue', + 'PropertyQuota', + 'QuotaStatus', + 'FunnelBreakdown', + 'FunnelNextAction', + 'Funnel', + 'FunnelStep', + 'FunnelSubReport', + 'UserSegment', + 'UserSegmentCriteria', + 'UserSegmentConditionGroup', + 'UserSegmentSequenceGroup', + 'UserSequenceStep', + 'UserSegmentExclusion', + 'SessionSegment', + 'SessionSegmentCriteria', + 'SessionSegmentConditionGroup', + 'SessionSegmentExclusion', + 'EventSegment', + 'EventSegmentCriteria', + 'EventSegmentConditionGroup', + 'EventSegmentExclusion', + 'Segment', + 'SegmentFilterExpression', + 'SegmentFilterExpressionList', + 'SegmentFilter', + 'SegmentFilterScoping', + 'SegmentEventFilter', + 'SegmentParameterFilterExpression', + 'SegmentParameterFilterExpressionList', + 'SegmentParameterFilter', + 'SegmentParameterFilterScoping', + 'FunnelFilterExpression', + 'FunnelFilterExpressionList', + 'FunnelFieldFilter', + 'FunnelEventFilter', + 'FunnelParameterFilterExpression', + 'FunnelParameterFilterExpressionList', + 'FunnelParameterFilter', + 'FunnelResponseMetadata', + 'SamplingMetadata', + }, +) + + +class UserCriteriaScoping(proto.Enum): + r"""Scoping specifies which events are considered when evaluating + if a user meets a criteria. + """ + USER_CRITERIA_SCOPING_UNSPECIFIED = 0 + USER_CRITERIA_WITHIN_SAME_EVENT = 1 + USER_CRITERIA_WITHIN_SAME_SESSION = 2 + USER_CRITERIA_ACROSS_ALL_SESSIONS = 3 + + +class UserExclusionDuration(proto.Enum): + r"""Enumerates options for how long an exclusion will last if a user + matches the ``userExclusionCriteria``. + """ + USER_EXCLUSION_DURATION_UNSPECIFIED = 0 + USER_EXCLUSION_TEMPORARY = 1 + USER_EXCLUSION_PERMANENT = 2 + + +class SessionCriteriaScoping(proto.Enum): + r"""Scoping specifies which events are considered when evaluating + if a session meets a criteria. + """ + SESSION_CRITERIA_SCOPING_UNSPECIFIED = 0 + SESSION_CRITERIA_WITHIN_SAME_EVENT = 1 + SESSION_CRITERIA_WITHIN_SAME_SESSION = 2 + + +class SessionExclusionDuration(proto.Enum): + r"""Enumerates options for how long an exclusion will last if a session + matches the ``sessionExclusionCriteria``. + """ + SESSION_EXCLUSION_DURATION_UNSPECIFIED = 0 + SESSION_EXCLUSION_TEMPORARY = 1 + SESSION_EXCLUSION_PERMANENT = 2 + + +class EventCriteriaScoping(proto.Enum): + r"""Scoping specifies which events are considered when evaluating + if an event meets a criteria. + """ + EVENT_CRITERIA_SCOPING_UNSPECIFIED = 0 + EVENT_CRITERIA_WITHIN_SAME_EVENT = 1 + + +class EventExclusionDuration(proto.Enum): + r"""Enumerates options for how long an exclusion will last if an event + matches the ``eventExclusionCriteria``. + """ + EVENT_EXCLUSION_DURATION_UNSPECIFIED = 0 + EVENT_EXCLUSION_PERMANENT = 1 + + +class MetricType(proto.Enum): + r"""A metric's value type.""" + METRIC_TYPE_UNSPECIFIED = 0 + TYPE_INTEGER = 1 + TYPE_FLOAT = 2 + TYPE_SECONDS = 4 + TYPE_MILLISECONDS = 5 + TYPE_MINUTES = 6 + TYPE_HOURS = 7 + TYPE_STANDARD = 8 + TYPE_CURRENCY = 9 + TYPE_FEET = 10 + TYPE_MILES = 11 + TYPE_METERS = 12 + TYPE_KILOMETERS = 13 + + +class DateRange(proto.Message): + r"""A contiguous set of days: startDate, startDate + 1, ..., + endDate. Requests are allowed up to 4 date ranges. + + Attributes: + start_date (str): + The inclusive start date for the query in the format + ``YYYY-MM-DD``. Cannot be after ``end_date``. The format + ``NdaysAgo``, ``yesterday``, or ``today`` is also accepted, + and in that case, the date is inferred based on the + property's reporting time zone. + end_date (str): + The inclusive end date for the query in the format + ``YYYY-MM-DD``. Cannot be before ``start_date``. The format + ``NdaysAgo``, ``yesterday``, or ``today`` is also accepted, + and in that case, the date is inferred based on the + property's reporting time zone. + name (str): + Assigns a name to this date range. The dimension + ``dateRange`` is valued to this name in a report response. + If set, cannot begin with ``date_range_`` or ``RESERVED_``. + If not set, date ranges are named by their zero based index + in the request: ``date_range_0``, ``date_range_1``, etc. + """ + + start_date: str = proto.Field( + proto.STRING, + number=1, + ) + end_date: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + +class Dimension(proto.Message): + r"""Dimensions are attributes of your data. For example, the + dimension city indicates the city from which an event + originates. Dimension values in report responses are strings; + for example, the city could be "Paris" or "New York". + + Attributes: + name (str): + The name of the dimension. See the `API + Dimensions `__ + for the list of dimension names. + + If ``dimensionExpression`` is specified, ``name`` can be any + string that you would like within the allowed character set. + For example if a ``dimensionExpression`` concatenates + ``country`` and ``city``, you could call that dimension + ``countryAndCity``. Dimension names that you choose must + match the regular expression ``^[a-zA-Z0-9_]$``. + + Dimensions are referenced by ``name`` in + ``dimensionFilter``, ``orderBys``, ``dimensionExpression``, + and ``pivots``. + dimension_expression (google.analytics.data_v1alpha.types.DimensionExpression): + One dimension can be the result of an + expression of multiple dimensions. For example, + dimension "country, city": concatenate(country, + ", ", city). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + dimension_expression: 'DimensionExpression' = proto.Field( + proto.MESSAGE, + number=2, + message='DimensionExpression', + ) + + +class DimensionExpression(proto.Message): + r"""Used to express a dimension which is the result of a formula of + multiple dimensions. Example usages: + + 1) lower_case(dimension) + 2) concatenate(dimension1, symbol, dimension2). + + 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: + lower_case (google.analytics.data_v1alpha.types.DimensionExpression.CaseExpression): + Used to convert a dimension value to lower + case. + + This field is a member of `oneof`_ ``one_expression``. + upper_case (google.analytics.data_v1alpha.types.DimensionExpression.CaseExpression): + Used to convert a dimension value to upper + case. + + This field is a member of `oneof`_ ``one_expression``. + concatenate (google.analytics.data_v1alpha.types.DimensionExpression.ConcatenateExpression): + Used to combine dimension values to a single + dimension. For example, dimension "country, + city": concatenate(country, ", ", city). + + This field is a member of `oneof`_ ``one_expression``. + """ + + class CaseExpression(proto.Message): + r"""Used to convert a dimension value to a single case. + + Attributes: + dimension_name (str): + Name of a dimension. The name must refer back + to a name in dimensions field of the request. + """ + + dimension_name: str = proto.Field( + proto.STRING, + number=1, + ) + + class ConcatenateExpression(proto.Message): + r"""Used to combine dimension values to a single dimension. + + Attributes: + dimension_names (MutableSequence[str]): + Names of dimensions. The names must refer + back to names in the dimensions field of the + request. + delimiter (str): + The delimiter placed between dimension names. + + Delimiters are often single characters such as "|" or "," + but can be longer strings. If a dimension value contains the + delimiter, both will be present in response with no + distinction. For example if dimension 1 value = "US,FR", + dimension 2 value = "JP", and delimiter = ",", then the + response will contain "US,FR,JP". + """ + + dimension_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + delimiter: str = proto.Field( + proto.STRING, + number=2, + ) + + lower_case: CaseExpression = proto.Field( + proto.MESSAGE, + number=4, + oneof='one_expression', + message=CaseExpression, + ) + upper_case: CaseExpression = proto.Field( + proto.MESSAGE, + number=5, + oneof='one_expression', + message=CaseExpression, + ) + concatenate: ConcatenateExpression = proto.Field( + proto.MESSAGE, + number=6, + oneof='one_expression', + message=ConcatenateExpression, + ) + + +class FilterExpression(proto.Message): + r"""To express dimension or metric filters. The fields in the + same FilterExpression 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.data_v1alpha.types.FilterExpressionList): + The FilterExpressions in and_group have an AND relationship. + + This field is a member of `oneof`_ ``expr``. + or_group (google.analytics.data_v1alpha.types.FilterExpressionList): + The FilterExpressions in or_group have an OR relationship. + + This field is a member of `oneof`_ ``expr``. + not_expression (google.analytics.data_v1alpha.types.FilterExpression): + The FilterExpression is NOT of not_expression. + + This field is a member of `oneof`_ ``expr``. + filter (google.analytics.data_v1alpha.types.Filter): + 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`_ ``expr``. + """ + + and_group: 'FilterExpressionList' = proto.Field( + proto.MESSAGE, + number=1, + oneof='expr', + message='FilterExpressionList', + ) + or_group: 'FilterExpressionList' = proto.Field( + proto.MESSAGE, + number=2, + oneof='expr', + message='FilterExpressionList', + ) + not_expression: 'FilterExpression' = proto.Field( + proto.MESSAGE, + number=3, + oneof='expr', + message='FilterExpression', + ) + filter: 'Filter' = proto.Field( + proto.MESSAGE, + number=4, + oneof='expr', + message='Filter', + ) + + +class FilterExpressionList(proto.Message): + r"""A list of filter expressions. + + Attributes: + expressions (MutableSequence[google.analytics.data_v1alpha.types.FilterExpression]): + A list of filter expressions. + """ + + expressions: MutableSequence['FilterExpression'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='FilterExpression', + ) + + +class Filter(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: + field_name (str): + The dimension name or metric name. Must be a + name defined in dimensions or metrics. + string_filter (google.analytics.data_v1alpha.types.StringFilter): + Strings related filter. + + This field is a member of `oneof`_ ``one_filter``. + in_list_filter (google.analytics.data_v1alpha.types.InListFilter): + A filter for in list values. + + This field is a member of `oneof`_ ``one_filter``. + numeric_filter (google.analytics.data_v1alpha.types.NumericFilter): + A filter for numeric or date values. + + This field is a member of `oneof`_ ``one_filter``. + between_filter (google.analytics.data_v1alpha.types.BetweenFilter): + A filter for between two values. + + This field is a member of `oneof`_ ``one_filter``. + """ + + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + 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', + ) + + +class StringFilter(proto.Message): + r"""The filter for string + + Attributes: + match_type (google.analytics.data_v1alpha.types.StringFilter.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""" + 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 InListFilter(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 NumericFilter(proto.Message): + r"""Filters for numeric or date values. + + Attributes: + operation (google.analytics.data_v1alpha.types.NumericFilter.Operation): + The operation type for this filter. + value (google.analytics.data_v1alpha.types.NumericValue): + A numeric value or a date value. + """ + class Operation(proto.Enum): + r"""The operation applied to a numeric filter""" + 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 BetweenFilter(proto.Message): + r"""To express that the result needs to be between two numbers + (inclusive). + + Attributes: + from_value (google.analytics.data_v1alpha.types.NumericValue): + Begins with this number. + to_value (google.analytics.data_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 DimensionHeader(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: + name (str): + The dimension's name. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class MetricHeader(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: + name (str): + The metric's name. + type_ (google.analytics.data_v1alpha.types.MetricType): + The metric's data type. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: 'MetricType' = proto.Field( + proto.ENUM, + number=2, + enum='MetricType', + ) + + +class Row(proto.Message): + r"""Report data for each row. For example if RunReportRequest contains: + + .. code:: none + + "dimensions": [ + { + "name": "eventName" + }, + { + "name": "countryId" + } + ], + "metrics": [ + { + "name": "eventCount" + } + ] + + One row with 'in_app_purchase' as the eventName, 'JP' as the + countryId, and 15 as the eventCount, would be: + + .. code:: none + + "dimensionValues": [ + { + "value": "in_app_purchase" + }, + { + "value": "JP" + } + ], + "metricValues": [ + { + "value": "15" + } + ] + + Attributes: + dimension_values (MutableSequence[google.analytics.data_v1alpha.types.DimensionValue]): + List of requested dimension values. In a PivotReport, + dimension_values are only listed for dimensions included in + a pivot. + metric_values (MutableSequence[google.analytics.data_v1alpha.types.MetricValue]): + List of requested visible metric values. + """ + + dimension_values: MutableSequence['DimensionValue'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='DimensionValue', + ) + metric_values: MutableSequence['MetricValue'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='MetricValue', + ) + + +class DimensionValue(proto.Message): + r"""The value of a dimension. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (str): + Value as a string if the dimension type is a + string. + + This field is a member of `oneof`_ ``one_value``. + """ + + value: str = proto.Field( + proto.STRING, + number=1, + oneof='one_value', + ) + + +class MetricValue(proto.Message): + r"""The value of a metric. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (str): + Measurement value. See MetricHeader for type. + + This field is a member of `oneof`_ ``one_value``. + """ + + value: str = proto.Field( + proto.STRING, + number=4, + oneof='one_value', + ) + + +class PropertyQuota(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.data_v1alpha.types.QuotaStatus): + Standard Analytics Properties can use up to + 25,000 tokens per day; Analytics 360 Properties + can use 250,000 tokens per day. Most requests + consume fewer than 10 tokens. + tokens_per_hour (google.analytics.data_v1alpha.types.QuotaStatus): + Standard Analytics Properties can use up to + 5,000 tokens per hour; Analytics 360 Properties + can use 50,000 tokens per hour. An API request + consumes a single number of tokens, and that + number is deducted from both the hourly and + daily quotas. + concurrent_requests (google.analytics.data_v1alpha.types.QuotaStatus): + Standard Analytics Properties can send up to + 10 concurrent requests; Analytics 360 Properties + can use up to 50 concurrent requests. + server_errors_per_project_per_hour (google.analytics.data_v1alpha.types.QuotaStatus): + Standard Analytics Properties and cloud + project pairs can have up to 10 server errors + per hour; Analytics 360 Properties and cloud + project pairs can have up to 50 server errors + per hour. + potentially_thresholded_requests_per_hour (google.analytics.data_v1alpha.types.QuotaStatus): + Analytics Properties can send up to 120 + requests with potentially thresholded dimensions + per hour. In a batch request, each report + request is individually counted for this quota + if the request contains potentially thresholded + dimensions. + """ + + tokens_per_day: 'QuotaStatus' = proto.Field( + proto.MESSAGE, + number=1, + message='QuotaStatus', + ) + tokens_per_hour: 'QuotaStatus' = proto.Field( + proto.MESSAGE, + number=2, + message='QuotaStatus', + ) + concurrent_requests: 'QuotaStatus' = proto.Field( + proto.MESSAGE, + number=3, + message='QuotaStatus', + ) + server_errors_per_project_per_hour: 'QuotaStatus' = proto.Field( + proto.MESSAGE, + number=4, + message='QuotaStatus', + ) + potentially_thresholded_requests_per_hour: 'QuotaStatus' = proto.Field( + proto.MESSAGE, + number=5, + message='QuotaStatus', + ) + + +class QuotaStatus(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, + ) + + +class FunnelBreakdown(proto.Message): + r"""Breakdowns add a dimension to the funnel table sub report + response. + + Attributes: + breakdown_dimension (google.analytics.data_v1alpha.types.Dimension): + The dimension column added to the funnel table sub report + response. The breakdown dimension breaks down each funnel + step. A valid ``breakdownDimension`` is required if + ``funnelBreakdown`` is specified. + limit (int): + The maximum number of distinct values of the breakdown + dimension to return in the response. A ``limit`` of ``5`` is + used if limit is not specified. Limit must exceed zero and + cannot exceed 15. + + This field is a member of `oneof`_ ``_limit``. + """ + + breakdown_dimension: 'Dimension' = proto.Field( + proto.MESSAGE, + number=1, + message='Dimension', + ) + limit: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + + +class FunnelNextAction(proto.Message): + r"""Next actions state the value for a dimension after the user has + achieved a step but before the same user has achieved the next step. + For example if the ``nextActionDimension`` is ``eventName``, then + ``nextActionDimension`` in the ``i``\ th funnel step row will return + first event after the event that qualified the user into the + ``i``\ th funnel step but before the user achieved the ``i+1``\ th + funnel step. + + Attributes: + next_action_dimension (google.analytics.data_v1alpha.types.Dimension): + The dimension column added to the funnel visualization sub + report response. The next action dimension returns the next + dimension value of this dimension after the user has + attained the ``i``\ th funnel step. + + ``nextActionDimension`` currently only supports + ``eventName`` and most Page / Screen dimensions like + ``pageTitle`` and ``pagePath``. ``nextActionDimension`` + cannot be a dimension expression. + limit (int): + The maximum number of distinct values of the breakdown + dimension to return in the response. A ``limit`` of ``5`` is + used if limit is not specified. Limit must exceed zero and + cannot exceed 5. + + This field is a member of `oneof`_ ``_limit``. + """ + + next_action_dimension: 'Dimension' = proto.Field( + proto.MESSAGE, + number=1, + message='Dimension', + ) + limit: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + + +class Funnel(proto.Message): + r"""Configures the funnel in a funnel report request. A funnel + reports on users as they pass through a sequence of steps. + Funnel exploration lets you visualize the steps your users take + to complete a task and quickly see how well they are succeeding + or failing at each step. For example, how do prospects become + shoppers and then become buyers? How do one time buyers become + repeat buyers? With this information, you can improve + inefficient or abandoned customer journeys. + + Attributes: + is_open_funnel (bool): + In an open funnel, users can enter the funnel + in any step, and in a closed funnel, users must + enter the funnel in the first step. Optional. If + unspecified, a closed funnel is used. + steps (MutableSequence[google.analytics.data_v1alpha.types.FunnelStep]): + The sequential steps of this funnel. + """ + + is_open_funnel: bool = proto.Field( + proto.BOOL, + number=1, + ) + steps: MutableSequence['FunnelStep'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='FunnelStep', + ) + + +class FunnelStep(proto.Message): + r"""Steps define the user journey you want to measure. Steps + contain one or more conditions that your users must meet to be + included in that step of the funnel journey. + + Attributes: + name (str): + The distinctive name for this step. If unspecified, steps + will be named by a 1 based indexed name (i.e. "0. ", "1. ", + etc.). This name defines string value returned by the + ``funnelStepName`` dimension. For example, specifying + ``name = Purchase`` in the request's third funnel step will + produce ``3. Purchase`` in the funnel report response. + is_directly_followed_by (bool): + If true, this step must directly follow the previous step. + If false, there can be events between the previous step and + this step. If unspecified, ``isDirectlyFollowedBy`` is + treated as false. + within_duration_from_prior_step (google.protobuf.duration_pb2.Duration): + If specified, this step must complete within this duration + of the completion of the prior step. + ``withinDurationFromPriorStep`` is inclusive of the endpoint + at the microsecond granularity. For example a duration of 5 + seconds can be completed at 4.9 or 5.0 seconds, but not 5 + seconds and 1 microsecond. + + ``withinDurationFromPriorStep`` is optional, and if + unspecified, steps may be separated by any time duration. + + This field is a member of `oneof`_ ``_within_duration_from_prior_step``. + filter_expression (google.analytics.data_v1alpha.types.FunnelFilterExpression): + The condition that your users must meet to be + included in this step of the funnel journey. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + is_directly_followed_by: bool = proto.Field( + proto.BOOL, + number=2, + ) + within_duration_from_prior_step: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message=duration_pb2.Duration, + ) + filter_expression: 'FunnelFilterExpression' = proto.Field( + proto.MESSAGE, + number=4, + message='FunnelFilterExpression', + ) + + +class FunnelSubReport(proto.Message): + r"""Funnel sub reports contain the dimension and metric data + values. For example, 12 users reached the second step of the + funnel. + + Attributes: + dimension_headers (MutableSequence[google.analytics.data_v1alpha.types.DimensionHeader]): + Describes dimension columns. Funnel reports + always include the funnel step dimension in sub + report responses. Additional dimensions like + breakdowns, dates, and next actions may be + present in the response if requested. + metric_headers (MutableSequence[google.analytics.data_v1alpha.types.MetricHeader]): + Describes metric columns. Funnel reports + always include active users in sub report + responses. The funnel table includes additional + metrics like completion rate, abandonments, and + abandonments rate. + rows (MutableSequence[google.analytics.data_v1alpha.types.Row]): + Rows of dimension value combinations and + metric values in the report. + metadata (google.analytics.data_v1alpha.types.FunnelResponseMetadata): + Metadata for the funnel report. + """ + + dimension_headers: MutableSequence['DimensionHeader'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='DimensionHeader', + ) + metric_headers: MutableSequence['MetricHeader'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='MetricHeader', + ) + rows: MutableSequence['Row'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Row', + ) + metadata: 'FunnelResponseMetadata' = proto.Field( + proto.MESSAGE, + number=4, + message='FunnelResponseMetadata', + ) + + +class UserSegment(proto.Message): + r"""User segments are subsets of users who engaged with your site + or app. For example, users who have previously purchased; users + who added items to their shopping carts, but didn’t complete a + purchase. + + Attributes: + user_inclusion_criteria (google.analytics.data_v1alpha.types.UserSegmentCriteria): + Defines which users are included in this + segment. Optional. + exclusion (google.analytics.data_v1alpha.types.UserSegmentExclusion): + Defines which users are excluded in this + segment. Optional. + """ + + user_inclusion_criteria: 'UserSegmentCriteria' = proto.Field( + proto.MESSAGE, + number=1, + message='UserSegmentCriteria', + ) + exclusion: 'UserSegmentExclusion' = proto.Field( + proto.MESSAGE, + number=2, + message='UserSegmentExclusion', + ) + + +class UserSegmentCriteria(proto.Message): + r"""A user matches a criteria if the user's events meet the + conditions in the criteria. + + Attributes: + and_condition_groups (MutableSequence[google.analytics.data_v1alpha.types.UserSegmentConditionGroup]): + A user matches this criteria if the user matches each of + these ``andConditionGroups`` and each of the + ``andSequenceGroups``. ``andConditionGroups`` may be empty + if ``andSequenceGroups`` are specified. + and_sequence_groups (MutableSequence[google.analytics.data_v1alpha.types.UserSegmentSequenceGroup]): + A user matches this criteria if the user matches each of + these ``andSequenceGroups`` and each of the + ``andConditionGroups``. ``andSequenceGroups`` may be empty + if ``andConditionGroups`` are specified. + """ + + and_condition_groups: MutableSequence['UserSegmentConditionGroup'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='UserSegmentConditionGroup', + ) + and_sequence_groups: MutableSequence['UserSegmentSequenceGroup'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='UserSegmentSequenceGroup', + ) + + +class UserSegmentConditionGroup(proto.Message): + r"""Conditions tell Analytics what data to include in or exclude + from the segment. + + Attributes: + condition_scoping (google.analytics.data_v1alpha.types.UserCriteriaScoping): + Data is included or excluded from the segment based on if it + matches the condition group. This scoping defines how many + events the ``segmentFilterExpression`` is evaluated on + before the condition group is determined to be matched or + not. For example if + ``conditionScoping = USER_CRITERIA_WITHIN_SAME_SESSION``, + the expression is evaluated on all events in a session, and + then, the condition group is determined to be matched or not + for this user. For example if + ``conditionScoping = USER_CRITERIA_WITHIN_SAME_EVENT``, the + expression is evaluated on a single event, and then, the + condition group is determined to be matched or not for this + user. + + Optional. If unspecified, + ``conditionScoping = ACROSS_ALL_SESSIONS`` is used. + segment_filter_expression (google.analytics.data_v1alpha.types.SegmentFilterExpression): + Data is included or excluded from the segment + based on if it matches this expression. + Expressions express criteria on dimension, + metrics, and/or parameters. + """ + + condition_scoping: 'UserCriteriaScoping' = proto.Field( + proto.ENUM, + number=1, + enum='UserCriteriaScoping', + ) + segment_filter_expression: 'SegmentFilterExpression' = proto.Field( + proto.MESSAGE, + number=2, + message='SegmentFilterExpression', + ) + + +class UserSegmentSequenceGroup(proto.Message): + r"""Define conditions that must occur in a specific order for the + user to be a member of the segment. + + Attributes: + sequence_scoping (google.analytics.data_v1alpha.types.UserCriteriaScoping): + All sequence steps must be satisfied in the scoping for the + user to match the sequence. For example if + ``sequenceScoping = USER_CRITERIA_WITHIN_SAME_SESSION``, all + sequence steps must complete within one session for the user + to match the sequence. + ``sequenceScoping = USER_CRITERIA_WITHIN_SAME_EVENT`` is not + supported. + + Optional. If unspecified, + ``conditionScoping = ACROSS_ALL_SESSIONS`` is used. + sequence_maximum_duration (google.protobuf.duration_pb2.Duration): + Defines the time period in which the whole sequence must + occur; for example, 30 Minutes. ``sequenceMaximumDuration`` + is inclusive of the endpoint at the microsecond granularity. + For example a sequence with a maximum duration of 5 seconds + can be completed at 4.9 or 5.0 seconds, but not 5 seconds + and 1 microsecond. + + ``sequenceMaximumDuration`` is optional, and if unspecified, + sequences can be completed in any time duration. + user_sequence_steps (MutableSequence[google.analytics.data_v1alpha.types.UserSequenceStep]): + An ordered sequence of condition steps. A user's events must + complete each step in order for the user to match the + ``UserSegmentSequenceGroup``. + """ + + sequence_scoping: 'UserCriteriaScoping' = proto.Field( + proto.ENUM, + number=1, + enum='UserCriteriaScoping', + ) + sequence_maximum_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + user_sequence_steps: MutableSequence['UserSequenceStep'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='UserSequenceStep', + ) + + +class UserSequenceStep(proto.Message): + r"""A condition that must occur in the specified step order for + this user to match the sequence. + + Attributes: + is_directly_followed_by (bool): + If true, the event satisfying this step must be the very + next event after the event satifying the last step. If + false, this step indirectly follows the prior step; for + example, there may be events between the prior step and this + step. ``isDirectlyFollowedBy`` must be false for the first + step. + step_scoping (google.analytics.data_v1alpha.types.UserCriteriaScoping): + This sequence step must be satisfied in the scoping for the + user to match the sequence. For example if + ``sequenceScoping = WITHIN_SAME_SESSION``, this sequence + steps must complete within one session for the user to match + the sequence. ``stepScoping = ACROSS_ALL_SESSIONS`` is only + allowed if the ``sequenceScoping = ACROSS_ALL_SESSIONS``. + + Optional. If unspecified, ``stepScoping`` uses the same + ``UserCriteriaScoping`` as the ``sequenceScoping``. + segment_filter_expression (google.analytics.data_v1alpha.types.SegmentFilterExpression): + A user matches this sequence step if their + events match this expression. Expressions + express criteria on dimension, metrics, and/or + parameters. + """ + + is_directly_followed_by: bool = proto.Field( + proto.BOOL, + number=1, + ) + step_scoping: 'UserCriteriaScoping' = proto.Field( + proto.ENUM, + number=2, + enum='UserCriteriaScoping', + ) + segment_filter_expression: 'SegmentFilterExpression' = proto.Field( + proto.MESSAGE, + number=3, + message='SegmentFilterExpression', + ) + + +class UserSegmentExclusion(proto.Message): + r"""Specifies which users are excluded in this segment. + + Attributes: + user_exclusion_duration (google.analytics.data_v1alpha.types.UserExclusionDuration): + Specifies how long an exclusion will last if a user matches + the ``userExclusionCriteria``. + + Optional. If unspecified, ``userExclusionDuration`` of + ``USER_EXCLUSION_TEMPORARY`` is used. + user_exclusion_criteria (google.analytics.data_v1alpha.types.UserSegmentCriteria): + If a user meets this condition, the user is excluded from + membership in the segment for the ``userExclusionDuration``. + """ + + user_exclusion_duration: 'UserExclusionDuration' = proto.Field( + proto.ENUM, + number=1, + enum='UserExclusionDuration', + ) + user_exclusion_criteria: 'UserSegmentCriteria' = proto.Field( + proto.MESSAGE, + number=2, + message='UserSegmentCriteria', + ) + + +class SessionSegment(proto.Message): + r"""Session segments are subsets of the sessions that occurred on + your site or app: for example, all the sessions that originated + from a particular advertising campaign. + + Attributes: + session_inclusion_criteria (google.analytics.data_v1alpha.types.SessionSegmentCriteria): + Defines which sessions are included in this + segment. Optional. + exclusion (google.analytics.data_v1alpha.types.SessionSegmentExclusion): + Defines which sessions are excluded in this + segment. Optional. + """ + + session_inclusion_criteria: 'SessionSegmentCriteria' = proto.Field( + proto.MESSAGE, + number=1, + message='SessionSegmentCriteria', + ) + exclusion: 'SessionSegmentExclusion' = proto.Field( + proto.MESSAGE, + number=2, + message='SessionSegmentExclusion', + ) + + +class SessionSegmentCriteria(proto.Message): + r"""A session matches a criteria if the session's events meet the + conditions in the criteria. + + Attributes: + and_condition_groups (MutableSequence[google.analytics.data_v1alpha.types.SessionSegmentConditionGroup]): + A session matches this criteria if the session matches each + of these ``andConditionGroups``. + """ + + and_condition_groups: MutableSequence['SessionSegmentConditionGroup'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SessionSegmentConditionGroup', + ) + + +class SessionSegmentConditionGroup(proto.Message): + r"""Conditions tell Analytics what data to include in or exclude + from the segment. + + Attributes: + condition_scoping (google.analytics.data_v1alpha.types.SessionCriteriaScoping): + Data is included or excluded from the segment based on if it + matches the condition group. This scoping defines how many + events the ``segmentFilterExpression`` is evaluated on + before the condition group is determined to be matched or + not. For example if + ``conditionScoping = SESSION_CRITERIA_WITHIN_SAME_SESSION``, + the expression is evaluated on all events in a session, and + then, the condition group is determined to be matched or not + for this session. For example if + ``conditionScoping = SESSION_CRITERIA_WITHIN_SAME_EVENT``, + the expression is evaluated on a single event, and then, the + condition group is determined to be matched or not for this + session. + + Optional. If unspecified, a ``conditionScoping`` of + ``WITHIN_SAME_SESSION`` is used. + segment_filter_expression (google.analytics.data_v1alpha.types.SegmentFilterExpression): + Data is included or excluded from the segment + based on if it matches this expression. + Expressions express criteria on dimension, + metrics, and/or parameters. + """ + + condition_scoping: 'SessionCriteriaScoping' = proto.Field( + proto.ENUM, + number=1, + enum='SessionCriteriaScoping', + ) + segment_filter_expression: 'SegmentFilterExpression' = proto.Field( + proto.MESSAGE, + number=2, + message='SegmentFilterExpression', + ) + + +class SessionSegmentExclusion(proto.Message): + r"""Specifies which sessions are excluded in this segment. + + Attributes: + session_exclusion_duration (google.analytics.data_v1alpha.types.SessionExclusionDuration): + Specifies how long an exclusion will last if a session + matches the ``sessionExclusionCriteria``. + + Optional. If unspecified, a ``sessionExclusionDuration`` of + ``SESSION_EXCLUSION_TEMPORARY`` is used. + session_exclusion_criteria (google.analytics.data_v1alpha.types.SessionSegmentCriteria): + If a session meets this condition, the session is excluded + from membership in the segment for the + ``sessionExclusionDuration``. + """ + + session_exclusion_duration: 'SessionExclusionDuration' = proto.Field( + proto.ENUM, + number=1, + enum='SessionExclusionDuration', + ) + session_exclusion_criteria: 'SessionSegmentCriteria' = proto.Field( + proto.MESSAGE, + number=2, + message='SessionSegmentCriteria', + ) + + +class EventSegment(proto.Message): + r"""Event segments are subsets of events that were triggered on your + site or app. for example, all purchase events made in a particular + location; app_exception events that occurred on a specific operating + system. + + Attributes: + event_inclusion_criteria (google.analytics.data_v1alpha.types.EventSegmentCriteria): + Defines which events are included in this + segment. Optional. + exclusion (google.analytics.data_v1alpha.types.EventSegmentExclusion): + Defines which events are excluded in this + segment. Optional. + """ + + event_inclusion_criteria: 'EventSegmentCriteria' = proto.Field( + proto.MESSAGE, + number=1, + message='EventSegmentCriteria', + ) + exclusion: 'EventSegmentExclusion' = proto.Field( + proto.MESSAGE, + number=2, + message='EventSegmentExclusion', + ) + + +class EventSegmentCriteria(proto.Message): + r"""An event matches a criteria if the event meet the conditions + in the criteria. + + Attributes: + and_condition_groups (MutableSequence[google.analytics.data_v1alpha.types.EventSegmentConditionGroup]): + An event matches this criteria if the event matches each of + these ``andConditionGroups``. + """ + + and_condition_groups: MutableSequence['EventSegmentConditionGroup'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='EventSegmentConditionGroup', + ) + + +class EventSegmentConditionGroup(proto.Message): + r"""Conditions tell Analytics what data to include in or exclude + from the segment. + + Attributes: + condition_scoping (google.analytics.data_v1alpha.types.EventCriteriaScoping): + ``conditionScoping`` should always be + ``EVENT_CRITERIA_WITHIN_SAME_EVENT``. + + Optional. If unspecified, a ``conditionScoping`` of + ``EVENT_CRITERIA_WITHIN_SAME_EVENT`` is used. + segment_filter_expression (google.analytics.data_v1alpha.types.SegmentFilterExpression): + Data is included or excluded from the segment + based on if it matches this expression. + Expressions express criteria on dimension, + metrics, and/or parameters. + """ + + condition_scoping: 'EventCriteriaScoping' = proto.Field( + proto.ENUM, + number=1, + enum='EventCriteriaScoping', + ) + segment_filter_expression: 'SegmentFilterExpression' = proto.Field( + proto.MESSAGE, + number=2, + message='SegmentFilterExpression', + ) + + +class EventSegmentExclusion(proto.Message): + r"""Specifies which events are excluded in this segment. + + Attributes: + event_exclusion_duration (google.analytics.data_v1alpha.types.EventExclusionDuration): + ``eventExclusionDuration`` should always be + ``PERMANENTLY_EXCLUDE``. + + Optional. If unspecified, an ``eventExclusionDuration`` of + ``EVENT_EXCLUSION_PERMANENT`` is used. + event_exclusion_criteria (google.analytics.data_v1alpha.types.EventSegmentCriteria): + If an event meets this condition, the event is excluded from + membership in the segment for the + ``eventExclusionDuration``. + """ + + event_exclusion_duration: 'EventExclusionDuration' = proto.Field( + proto.ENUM, + number=1, + enum='EventExclusionDuration', + ) + event_exclusion_criteria: 'EventSegmentCriteria' = proto.Field( + proto.MESSAGE, + number=2, + message='EventSegmentCriteria', + ) + + +class Segment(proto.Message): + r"""A segment is a subset of your Analytics data. For example, of your + entire set of users, one segment might be users from a particular + country or city. Another segment might be users who purchase a + particular line of products or who visit a specific part of your + site or trigger certain events in your app. + + To learn more, see `GA4 Segment + Builder `__. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The name for this segment. If unspecified, segments are + named "Segment". This name defines string value returned by + the ``segment`` dimension. The ``segment`` dimension + prefixes segment names by the 1-based index number of the + segment in the request (i.e. "1. Segment", "2. Segment", + etc.). + user_segment (google.analytics.data_v1alpha.types.UserSegment): + User segments are subsets of users who + engaged with your site or app. + + This field is a member of `oneof`_ ``one_segment_scope``. + session_segment (google.analytics.data_v1alpha.types.SessionSegment): + Session segments are subsets of the sessions + that occurred on your site or app. + + This field is a member of `oneof`_ ``one_segment_scope``. + event_segment (google.analytics.data_v1alpha.types.EventSegment): + Event segments are subsets of events that + were triggered on your site or app. + + This field is a member of `oneof`_ ``one_segment_scope``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + user_segment: 'UserSegment' = proto.Field( + proto.MESSAGE, + number=2, + oneof='one_segment_scope', + message='UserSegment', + ) + session_segment: 'SessionSegment' = proto.Field( + proto.MESSAGE, + number=3, + oneof='one_segment_scope', + message='SessionSegment', + ) + event_segment: 'EventSegment' = proto.Field( + proto.MESSAGE, + number=4, + oneof='one_segment_scope', + message='EventSegment', + ) + + +class SegmentFilterExpression(proto.Message): + r"""Expresses combinations of segment 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.data_v1alpha.types.SegmentFilterExpressionList): + The SegmentFilterExpression in ``andGroup`` have an AND + relationship. + + This field is a member of `oneof`_ ``expr``. + or_group (google.analytics.data_v1alpha.types.SegmentFilterExpressionList): + The SegmentFilterExpression in ``orGroup`` have an OR + relationship. + + This field is a member of `oneof`_ ``expr``. + not_expression (google.analytics.data_v1alpha.types.SegmentFilterExpression): + The SegmentFilterExpression is NOT of ``notExpression``. + + This field is a member of `oneof`_ ``expr``. + segment_filter (google.analytics.data_v1alpha.types.SegmentFilter): + A primitive segment filter. + + This field is a member of `oneof`_ ``expr``. + segment_event_filter (google.analytics.data_v1alpha.types.SegmentEventFilter): + Creates a filter that matches events of a + single event name. If a parameter filter + expression is specified, only the subset of + events that match both the single event name and + the parameter filter expressions match this + event filter. + + This field is a member of `oneof`_ ``expr``. + """ + + and_group: 'SegmentFilterExpressionList' = proto.Field( + proto.MESSAGE, + number=1, + oneof='expr', + message='SegmentFilterExpressionList', + ) + or_group: 'SegmentFilterExpressionList' = proto.Field( + proto.MESSAGE, + number=2, + oneof='expr', + message='SegmentFilterExpressionList', + ) + not_expression: 'SegmentFilterExpression' = proto.Field( + proto.MESSAGE, + number=3, + oneof='expr', + message='SegmentFilterExpression', + ) + segment_filter: 'SegmentFilter' = proto.Field( + proto.MESSAGE, + number=4, + oneof='expr', + message='SegmentFilter', + ) + segment_event_filter: 'SegmentEventFilter' = proto.Field( + proto.MESSAGE, + number=5, + oneof='expr', + message='SegmentEventFilter', + ) + + +class SegmentFilterExpressionList(proto.Message): + r"""A list of segment filter expressions. + + Attributes: + expressions (MutableSequence[google.analytics.data_v1alpha.types.SegmentFilterExpression]): + The list of segment filter expressions + """ + + expressions: MutableSequence['SegmentFilterExpression'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SegmentFilterExpression', + ) + + +class SegmentFilter(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: + field_name (str): + The dimension name or metric name. + string_filter (google.analytics.data_v1alpha.types.StringFilter): + Strings related filter. + + This field is a member of `oneof`_ ``one_filter``. + in_list_filter (google.analytics.data_v1alpha.types.InListFilter): + A filter for in list values. + + This field is a member of `oneof`_ ``one_filter``. + numeric_filter (google.analytics.data_v1alpha.types.NumericFilter): + A filter for numeric or date values. + + This field is a member of `oneof`_ ``one_filter``. + between_filter (google.analytics.data_v1alpha.types.BetweenFilter): + A filter for between two values. + + This field is a member of `oneof`_ ``one_filter``. + filter_scoping (google.analytics.data_v1alpha.types.SegmentFilterScoping): + Specifies the scope for the filter. + """ + + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + string_filter: 'StringFilter' = proto.Field( + proto.MESSAGE, + number=4, + oneof='one_filter', + message='StringFilter', + ) + in_list_filter: 'InListFilter' = proto.Field( + proto.MESSAGE, + number=5, + oneof='one_filter', + message='InListFilter', + ) + numeric_filter: 'NumericFilter' = proto.Field( + proto.MESSAGE, + number=6, + oneof='one_filter', + message='NumericFilter', + ) + between_filter: 'BetweenFilter' = proto.Field( + proto.MESSAGE, + number=7, + oneof='one_filter', + message='BetweenFilter', + ) + filter_scoping: 'SegmentFilterScoping' = proto.Field( + proto.MESSAGE, + number=8, + message='SegmentFilterScoping', + ) + + +class SegmentFilterScoping(proto.Message): + r"""Scopings specify how the dimensions & metrics of multiple + events should be considered when evaluating a segment filter. + + Attributes: + at_any_point_in_time (bool): + If ``atAnyPointInTime`` is true, this filter evaluates to + true for all events if it evaluates to true for any event in + the date range of the request. + + This ``atAnyPointInTime`` parameter does not extend the date + range of events in the report. If ``atAnyPointInTime`` is + true, only events within the report's date range are + considered when evaluating this filter. + + This ``atAnyPointInTime`` is only able to be specified if + the criteria scoping is ``ACROSS_ALL_SESSIONS`` and is not + able to be specified in sequences. + + If the criteria scoping is ``ACROSS_ALL_SESSIONS``, + ``atAnyPointInTime`` = false is used if unspecified. + + This field is a member of `oneof`_ ``_at_any_point_in_time``. + """ + + at_any_point_in_time: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + + +class SegmentEventFilter(proto.Message): + r"""Creates a filter that matches events of a single event name. + If a parameter filter expression 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): + This filter matches events of this single + event name. Event name is required. + + This field is a member of `oneof`_ ``_event_name``. + segment_parameter_filter_expression (google.analytics.data_v1alpha.types.SegmentParameterFilterExpression): + If specified, this filter matches events that + match both the single event name and the + parameter filter expressions. + Inside the parameter filter expression, only + parameter filters are available. + + This field is a member of `oneof`_ ``_segment_parameter_filter_expression``. + """ + + event_name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + segment_parameter_filter_expression: 'SegmentParameterFilterExpression' = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message='SegmentParameterFilterExpression', + ) + + +class SegmentParameterFilterExpression(proto.Message): + r"""Expresses combinations of segment filter on parameters. + + 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.data_v1alpha.types.SegmentParameterFilterExpressionList): + The SegmentParameterFilterExpression in ``andGroup`` have an + AND relationship. + + This field is a member of `oneof`_ ``expr``. + or_group (google.analytics.data_v1alpha.types.SegmentParameterFilterExpressionList): + The SegmentParameterFilterExpression in ``orGroup`` have an + OR relationship. + + This field is a member of `oneof`_ ``expr``. + not_expression (google.analytics.data_v1alpha.types.SegmentParameterFilterExpression): + The SegmentParameterFilterExpression is NOT of + ``notExpression``. + + This field is a member of `oneof`_ ``expr``. + segment_parameter_filter (google.analytics.data_v1alpha.types.SegmentParameterFilter): + A primitive segment parameter filter. + + This field is a member of `oneof`_ ``expr``. + """ + + and_group: 'SegmentParameterFilterExpressionList' = proto.Field( + proto.MESSAGE, + number=1, + oneof='expr', + message='SegmentParameterFilterExpressionList', + ) + or_group: 'SegmentParameterFilterExpressionList' = proto.Field( + proto.MESSAGE, + number=2, + oneof='expr', + message='SegmentParameterFilterExpressionList', + ) + not_expression: 'SegmentParameterFilterExpression' = proto.Field( + proto.MESSAGE, + number=3, + oneof='expr', + message='SegmentParameterFilterExpression', + ) + segment_parameter_filter: 'SegmentParameterFilter' = proto.Field( + proto.MESSAGE, + number=4, + oneof='expr', + message='SegmentParameterFilter', + ) + + +class SegmentParameterFilterExpressionList(proto.Message): + r"""A list of segment parameter filter expressions. + + Attributes: + expressions (MutableSequence[google.analytics.data_v1alpha.types.SegmentParameterFilterExpression]): + The list of segment parameter filter + expressions. + """ + + expressions: MutableSequence['SegmentParameterFilterExpression'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SegmentParameterFilterExpression', + ) + + +class SegmentParameterFilter(proto.Message): + r"""An expression to filter parameter values in a segment. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + event_parameter_name (str): + This filter will be evaluated on the specified event + parameter. Event parameters are logged as parameters of the + event. Event parameters include fields like + "firebase_screen" & "currency". + + Event parameters can only be used in segments & funnels and + can only be used in a descendent filter from an EventFilter. + In a descendent filter from an EventFilter either event or + item parameters should be used. + + This field is a member of `oneof`_ ``one_parameter``. + item_parameter_name (str): + This filter will be evaluated on the specified item + parameter. Item parameters are logged as parameters in the + item array. Item parameters include fields like "item_name" + & "item_category". + + Item parameters can only be used in segments & funnels and + can only be used in a descendent filter from an EventFilter. + In a descendent filter from an EventFilter either event or + item parameters should be used. + + Item parameters are only available in ecommerce events. To + learn more about ecommerce events, see the [Measure + ecommerce] + (https://developers.google.com/analytics/devguides/collection/ga4/ecommerce) + guide. + + This field is a member of `oneof`_ ``one_parameter``. + string_filter (google.analytics.data_v1alpha.types.StringFilter): + Strings related filter. + + This field is a member of `oneof`_ ``one_filter``. + in_list_filter (google.analytics.data_v1alpha.types.InListFilter): + A filter for in list values. + + This field is a member of `oneof`_ ``one_filter``. + numeric_filter (google.analytics.data_v1alpha.types.NumericFilter): + A filter for numeric or date values. + + This field is a member of `oneof`_ ``one_filter``. + between_filter (google.analytics.data_v1alpha.types.BetweenFilter): + A filter for between two values. + + This field is a member of `oneof`_ ``one_filter``. + filter_scoping (google.analytics.data_v1alpha.types.SegmentParameterFilterScoping): + Specifies the scope for the filter. + """ + + event_parameter_name: str = proto.Field( + proto.STRING, + number=1, + oneof='one_parameter', + ) + item_parameter_name: str = proto.Field( + proto.STRING, + number=2, + oneof='one_parameter', + ) + string_filter: 'StringFilter' = proto.Field( + proto.MESSAGE, + number=4, + oneof='one_filter', + message='StringFilter', + ) + in_list_filter: 'InListFilter' = proto.Field( + proto.MESSAGE, + number=5, + oneof='one_filter', + message='InListFilter', + ) + numeric_filter: 'NumericFilter' = proto.Field( + proto.MESSAGE, + number=6, + oneof='one_filter', + message='NumericFilter', + ) + between_filter: 'BetweenFilter' = proto.Field( + proto.MESSAGE, + number=7, + oneof='one_filter', + message='BetweenFilter', + ) + filter_scoping: 'SegmentParameterFilterScoping' = proto.Field( + proto.MESSAGE, + number=8, + message='SegmentParameterFilterScoping', + ) + + +class SegmentParameterFilterScoping(proto.Message): + r"""Scopings specify how multiple events should be considered + when evaluating a segment parameter filter. + + Attributes: + in_any_n_day_period (int): + Accumulates the parameter over the specified period of days + before applying the filter. Only supported if criteria + scoping is ``ACROSS_ALL_SESSIONS`` or + ``WITHIN_SAME_SESSION``. Only supported if the parameter is + ``event_count``. + + For example if ``inAnyNDayPeriod`` is 3, the event_name is + "purchase", the event parameter is "event_count", and the + Filter's criteria is greater than 5, this filter will + accumulate the event count of purchase events over every 3 + consecutive day period in the report's date range; a user + will pass this Filter's criteria to be included in this + segment if their count of purchase events exceeds 5 in any 3 + consecutive day period. For example, the periods 2021-11-01 + to 2021-11-03, 2021-11-02 to 2021-11-04, 2021-11-03 to + 2021-11-05, and etc. will be considered. + + The date range is not extended for the purpose of having a + full N day window near the start of the date range. For + example if a report is for 2021-11-01 to 2021-11-10 and + ``inAnyNDayPeriod`` = 3, the first two day period will be + effectively shortened because no event data outside the + report's date range will be read. For example, the first + four periods will effectively be: 2021-11-01 to 2021-11-01, + 2021-11-01 to 2021-11-02, 2021-11-01 to 2021-11-03, and + 2021-11-02 to 2021-11-04. + + ``inAnyNDayPeriod`` is optional. If not specified, the + ``segmentParameterFilter`` is applied to each event + individually. + + This field is a member of `oneof`_ ``_in_any_n_day_period``. + """ + + in_any_n_day_period: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + + +class FunnelFilterExpression(proto.Message): + r"""Expresses combinations of funnel 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.data_v1alpha.types.FunnelFilterExpressionList): + The FunnelFilterExpression in ``andGroup`` have an AND + relationship. + + This field is a member of `oneof`_ ``expr``. + or_group (google.analytics.data_v1alpha.types.FunnelFilterExpressionList): + The FunnelFilterExpression in ``orGroup`` have an OR + relationship. + + This field is a member of `oneof`_ ``expr``. + not_expression (google.analytics.data_v1alpha.types.FunnelFilterExpression): + The FunnelFilterExpression is NOT of ``notExpression``. + + This field is a member of `oneof`_ ``expr``. + funnel_field_filter (google.analytics.data_v1alpha.types.FunnelFieldFilter): + A funnel filter for a dimension or metric. + + This field is a member of `oneof`_ ``expr``. + funnel_event_filter (google.analytics.data_v1alpha.types.FunnelEventFilter): + Creates a filter that matches events of a + single event name. If a parameter filter + expression is specified, only the subset of + events that match both the single event name and + the parameter filter expressions match this + event filter. + + This field is a member of `oneof`_ ``expr``. + """ + + and_group: 'FunnelFilterExpressionList' = proto.Field( + proto.MESSAGE, + number=1, + oneof='expr', + message='FunnelFilterExpressionList', + ) + or_group: 'FunnelFilterExpressionList' = proto.Field( + proto.MESSAGE, + number=2, + oneof='expr', + message='FunnelFilterExpressionList', + ) + not_expression: 'FunnelFilterExpression' = proto.Field( + proto.MESSAGE, + number=3, + oneof='expr', + message='FunnelFilterExpression', + ) + funnel_field_filter: 'FunnelFieldFilter' = proto.Field( + proto.MESSAGE, + number=4, + oneof='expr', + message='FunnelFieldFilter', + ) + funnel_event_filter: 'FunnelEventFilter' = proto.Field( + proto.MESSAGE, + number=5, + oneof='expr', + message='FunnelEventFilter', + ) + + +class FunnelFilterExpressionList(proto.Message): + r"""A list of funnel filter expressions. + + Attributes: + expressions (MutableSequence[google.analytics.data_v1alpha.types.FunnelFilterExpression]): + The list of funnel filter expressions. + """ + + expressions: MutableSequence['FunnelFilterExpression'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='FunnelFilterExpression', + ) + + +class FunnelFieldFilter(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: + field_name (str): + The dimension name or metric name. + string_filter (google.analytics.data_v1alpha.types.StringFilter): + Strings related filter. + + This field is a member of `oneof`_ ``one_filter``. + in_list_filter (google.analytics.data_v1alpha.types.InListFilter): + A filter for in list values. + + This field is a member of `oneof`_ ``one_filter``. + numeric_filter (google.analytics.data_v1alpha.types.NumericFilter): + A filter for numeric or date values. + + This field is a member of `oneof`_ ``one_filter``. + between_filter (google.analytics.data_v1alpha.types.BetweenFilter): + A filter for between two values. + + This field is a member of `oneof`_ ``one_filter``. + """ + + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + string_filter: 'StringFilter' = proto.Field( + proto.MESSAGE, + number=4, + oneof='one_filter', + message='StringFilter', + ) + in_list_filter: 'InListFilter' = proto.Field( + proto.MESSAGE, + number=5, + oneof='one_filter', + message='InListFilter', + ) + numeric_filter: 'NumericFilter' = proto.Field( + proto.MESSAGE, + number=6, + oneof='one_filter', + message='NumericFilter', + ) + between_filter: 'BetweenFilter' = proto.Field( + proto.MESSAGE, + number=7, + oneof='one_filter', + message='BetweenFilter', + ) + + +class FunnelEventFilter(proto.Message): + r"""Creates a filter that matches events of a single event name. + If a parameter filter expression 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): + This filter matches events of this single + event name. Event name is required. + + This field is a member of `oneof`_ ``_event_name``. + funnel_parameter_filter_expression (google.analytics.data_v1alpha.types.FunnelParameterFilterExpression): + If specified, this filter matches events that + match both the single event name and the + parameter filter expressions. + Inside the parameter filter expression, only + parameter filters are available. + + This field is a member of `oneof`_ ``_funnel_parameter_filter_expression``. + """ + + event_name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + funnel_parameter_filter_expression: 'FunnelParameterFilterExpression' = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message='FunnelParameterFilterExpression', + ) + + +class FunnelParameterFilterExpression(proto.Message): + r"""Expresses combinations of funnel filters on parameters. + + 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.data_v1alpha.types.FunnelParameterFilterExpressionList): + The FunnelParameterFilterExpression in ``andGroup`` have an + AND relationship. + + This field is a member of `oneof`_ ``expr``. + or_group (google.analytics.data_v1alpha.types.FunnelParameterFilterExpressionList): + The FunnelParameterFilterExpression in ``orGroup`` have an + OR relationship. + + This field is a member of `oneof`_ ``expr``. + not_expression (google.analytics.data_v1alpha.types.FunnelParameterFilterExpression): + The FunnelParameterFilterExpression is NOT of + ``notExpression``. + + This field is a member of `oneof`_ ``expr``. + funnel_parameter_filter (google.analytics.data_v1alpha.types.FunnelParameterFilter): + A primitive funnel parameter filter. + + This field is a member of `oneof`_ ``expr``. + """ + + and_group: 'FunnelParameterFilterExpressionList' = proto.Field( + proto.MESSAGE, + number=1, + oneof='expr', + message='FunnelParameterFilterExpressionList', + ) + or_group: 'FunnelParameterFilterExpressionList' = proto.Field( + proto.MESSAGE, + number=2, + oneof='expr', + message='FunnelParameterFilterExpressionList', + ) + not_expression: 'FunnelParameterFilterExpression' = proto.Field( + proto.MESSAGE, + number=3, + oneof='expr', + message='FunnelParameterFilterExpression', + ) + funnel_parameter_filter: 'FunnelParameterFilter' = proto.Field( + proto.MESSAGE, + number=4, + oneof='expr', + message='FunnelParameterFilter', + ) + + +class FunnelParameterFilterExpressionList(proto.Message): + r"""A list of funnel parameter filter expressions. + + Attributes: + expressions (MutableSequence[google.analytics.data_v1alpha.types.FunnelParameterFilterExpression]): + The list of funnel parameter filter + expressions. + """ + + expressions: MutableSequence['FunnelParameterFilterExpression'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='FunnelParameterFilterExpression', + ) + + +class FunnelParameterFilter(proto.Message): + r"""An expression to filter parameter values in a funnel. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + event_parameter_name (str): + This filter will be evaluated on the specified event + parameter. Event parameters are logged as parameters of the + event. Event parameters include fields like + "firebase_screen" & "currency". + + Event parameters can only be used in segments & funnels and + can only be used in a descendent filter from an EventFilter. + In a descendent filter from an EventFilter either event or + item parameters should be used. + + This field is a member of `oneof`_ ``one_parameter``. + item_parameter_name (str): + This filter will be evaluated on the specified item + parameter. Item parameters are logged as parameters in the + item array. Item parameters include fields like "item_name" + & "item_category". + + Item parameters can only be used in segments & funnels and + can only be used in a descendent filter from an EventFilter. + In a descendent filter from an EventFilter either event or + item parameters should be used. + + Item parameters are only available in ecommerce events. To + learn more about ecommerce events, see the [Measure + ecommerce] + (https://developers.google.com/analytics/devguides/collection/ga4/ecommerce) + guide. + + This field is a member of `oneof`_ ``one_parameter``. + string_filter (google.analytics.data_v1alpha.types.StringFilter): + Strings related filter. + + This field is a member of `oneof`_ ``one_filter``. + in_list_filter (google.analytics.data_v1alpha.types.InListFilter): + A filter for in list values. + + This field is a member of `oneof`_ ``one_filter``. + numeric_filter (google.analytics.data_v1alpha.types.NumericFilter): + A filter for numeric or date values. + + This field is a member of `oneof`_ ``one_filter``. + between_filter (google.analytics.data_v1alpha.types.BetweenFilter): + A filter for between two values. + + This field is a member of `oneof`_ ``one_filter``. + """ + + event_parameter_name: str = proto.Field( + proto.STRING, + number=1, + oneof='one_parameter', + ) + item_parameter_name: str = proto.Field( + proto.STRING, + number=2, + oneof='one_parameter', + ) + string_filter: 'StringFilter' = proto.Field( + proto.MESSAGE, + number=4, + oneof='one_filter', + message='StringFilter', + ) + in_list_filter: 'InListFilter' = proto.Field( + proto.MESSAGE, + number=5, + oneof='one_filter', + message='InListFilter', + ) + numeric_filter: 'NumericFilter' = proto.Field( + proto.MESSAGE, + number=6, + oneof='one_filter', + message='NumericFilter', + ) + between_filter: 'BetweenFilter' = proto.Field( + proto.MESSAGE, + number=7, + oneof='one_filter', + message='BetweenFilter', + ) + + +class FunnelResponseMetadata(proto.Message): + r"""The funnel report's response metadata carries additional + information about the funnel report. + + Attributes: + sampling_metadatas (MutableSequence[google.analytics.data_v1alpha.types.SamplingMetadata]): + If funnel report results are + `sampled `__, + this describes what percentage of events were used in this + funnel report. One ``samplingMetadatas`` is populated for + each date range. Each ``samplingMetadatas`` corresponds to a + date range in order that date ranges were specified in the + request. + + However if the results are not sampled, this field will not + be defined. + """ + + sampling_metadatas: MutableSequence['SamplingMetadata'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SamplingMetadata', + ) + + +class SamplingMetadata(proto.Message): + r"""If funnel report results are + `sampled `__, + this metadata describes what percentage of events were used in this + funnel report for a date range. Sampling is the practice of + analyzing a subset of all data in order to uncover the meaningful + information in the larger data set. + + Attributes: + samples_read_count (int): + The total number of events read in this + sampled report for a date range. This is the + size of the subset this property's data that was + analyzed in this funnel report. + sampling_space_size (int): + The total number of events present in this property's data + that could have been analyzed in this funnel report for a + date range. Sampling uncovers the meaningful information + about the larger data set, and this is the size of the + larger data set. + + To calculate the percentage of available data that was used + in this funnel report, compute + ``samplesReadCount/samplingSpaceSize``. + """ + + samples_read_count: int = proto.Field( + proto.INT64, + number=1, + ) + sampling_space_size: int = proto.Field( + proto.INT64, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/mypy.ini b/owl-bot-staging/v1alpha/mypy.ini new file mode 100644 index 0000000..574c5ae --- /dev/null +++ b/owl-bot-staging/v1alpha/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1alpha/noxfile.py b/owl-bot-staging/v1alpha/noxfile.py new file mode 100644 index 0000000..b15c260 --- /dev/null +++ b/owl-bot-staging/v1alpha/noxfile.py @@ -0,0 +1,179 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.10" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/analytics/data_v1alpha/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.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, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_async.py new file mode 100644 index 0000000..aa67490 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RunFunnelReport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-data + + +# [START analyticsdata_v1alpha_generated_AlphaAnalyticsData_RunFunnelReport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 data_v1alpha + + +async def sample_run_funnel_report(): + # Create a client + client = data_v1alpha.AlphaAnalyticsDataAsyncClient() + + # Initialize request argument(s) + request = data_v1alpha.RunFunnelReportRequest( + ) + + # Make the request + response = await client.run_funnel_report(request=request) + + # Handle the response + print(response) + +# [END analyticsdata_v1alpha_generated_AlphaAnalyticsData_RunFunnelReport_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_sync.py new file mode 100644 index 0000000..d65d5da --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RunFunnelReport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-data + + +# [START analyticsdata_v1alpha_generated_AlphaAnalyticsData_RunFunnelReport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 data_v1alpha + + +def sample_run_funnel_report(): + # Create a client + client = data_v1alpha.AlphaAnalyticsDataClient() + + # Initialize request argument(s) + request = data_v1alpha.RunFunnelReportRequest( + ) + + # Make the request + response = client.run_funnel_report(request=request) + + # Handle the response + print(response) + +# [END analyticsdata_v1alpha_generated_AlphaAnalyticsData_RunFunnelReport_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json b/owl-bot-staging/v1alpha/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json new file mode 100644 index 0000000..037832d --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json @@ -0,0 +1,168 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.analytics.data.v1alpha", + "version": "v1alpha" + } + ], + "language": "PYTHON", + "name": "google-analytics-data", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.data_v1alpha.AlphaAnalyticsDataAsyncClient", + "shortName": "AlphaAnalyticsDataAsyncClient" + }, + "fullName": "google.analytics.data_v1alpha.AlphaAnalyticsDataAsyncClient.run_funnel_report", + "method": { + "fullName": "google.analytics.data.v1alpha.AlphaAnalyticsData.RunFunnelReport", + "service": { + "fullName": "google.analytics.data.v1alpha.AlphaAnalyticsData", + "shortName": "AlphaAnalyticsData" + }, + "shortName": "RunFunnelReport" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.data_v1alpha.types.RunFunnelReportRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.data_v1alpha.types.RunFunnelReportResponse", + "shortName": "run_funnel_report" + }, + "description": "Sample for RunFunnelReport", + "file": "analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsdata_v1alpha_generated_AlphaAnalyticsData_RunFunnelReport_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": "analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.data_v1alpha.AlphaAnalyticsDataClient", + "shortName": "AlphaAnalyticsDataClient" + }, + "fullName": "google.analytics.data_v1alpha.AlphaAnalyticsDataClient.run_funnel_report", + "method": { + "fullName": "google.analytics.data.v1alpha.AlphaAnalyticsData.RunFunnelReport", + "service": { + "fullName": "google.analytics.data.v1alpha.AlphaAnalyticsData", + "shortName": "AlphaAnalyticsData" + }, + "shortName": "RunFunnelReport" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.data_v1alpha.types.RunFunnelReportRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.data_v1alpha.types.RunFunnelReportResponse", + "shortName": "run_funnel_report" + }, + "description": "Sample for RunFunnelReport", + "file": "analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsdata_v1alpha_generated_AlphaAnalyticsData_RunFunnelReport_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": "analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1alpha/scripts/fixup_data_v1alpha_keywords.py b/owl-bot-staging/v1alpha/scripts/fixup_data_v1alpha_keywords.py new file mode 100644 index 0000000..8a3ca04 --- /dev/null +++ b/owl-bot-staging/v1alpha/scripts/fixup_data_v1alpha_keywords.py @@ -0,0 +1,176 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 dataCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'run_funnel_report': ('property', 'date_ranges', 'funnel', 'funnel_breakdown', 'funnel_next_action', 'funnel_visualization_type', 'segments', 'limit', 'dimension_filter', 'return_property_quota', ), + } + + 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=dataCallTransformer(), +): + """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 data 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/v1alpha/setup.py b/owl-bot-staging/v1alpha/setup.py new file mode 100644 index 0000000..6563668 --- /dev/null +++ b/owl-bot-staging/v1alpha/setup.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-analytics-data' + + +description = "Google Analytics Data API client library" + +version = {} +with open(os.path.join(package_root, 'google/analytics/data/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.33.2, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-google-analytics-data" + +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.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google"] +if "google.cloud" in packages: + namespaces.append("google.cloud") + +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", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/v1alpha/testing/constraints-3.10.txt b/owl-bot-staging/v1alpha/testing/constraints-3.10.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/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/v1alpha/testing/constraints-3.11.txt b/owl-bot-staging/v1alpha/testing/constraints-3.11.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/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/v1alpha/testing/constraints-3.7.txt b/owl-bot-staging/v1alpha/testing/constraints-3.7.txt new file mode 100644 index 0000000..aca9f2d --- /dev/null +++ b/owl-bot-staging/v1alpha/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +# This file is intentionally left empty to test the +# latest versions of dependencies. +google-api-core==1.33.2 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/v1alpha/testing/constraints-3.8.txt b/owl-bot-staging/v1alpha/testing/constraints-3.8.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/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/v1alpha/testing/constraints-3.9.txt b/owl-bot-staging/v1alpha/testing/constraints-3.9.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/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/v1alpha/tests/__init__.py b/owl-bot-staging/v1alpha/tests/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1alpha/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1alpha/tests/unit/__init__.py b/owl-bot-staging/v1alpha/tests/unit/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1alpha/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1alpha/tests/unit/gapic/data_v1alpha/__init__.py b/owl-bot-staging/v1alpha/tests/unit/gapic/data_v1alpha/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1alpha/tests/unit/gapic/data_v1alpha/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1alpha/tests/unit/gapic/data_v1alpha/test_alpha_analytics_data.py b/owl-bot-staging/v1alpha/tests/unit/gapic/data_v1alpha/test_alpha_analytics_data.py new file mode 100644 index 0000000..d0bffcc --- /dev/null +++ b/owl-bot-staging/v1alpha/tests/unit/gapic/data_v1alpha/test_alpha_analytics_data.py @@ -0,0 +1,1455 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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.data_v1alpha.services.alpha_analytics_data import AlphaAnalyticsDataAsyncClient +from google.analytics.data_v1alpha.services.alpha_analytics_data import AlphaAnalyticsDataClient +from google.analytics.data_v1alpha.services.alpha_analytics_data import transports +from google.analytics.data_v1alpha.types import analytics_data_api +from google.analytics.data_v1alpha.types import data +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AlphaAnalyticsDataClient._get_default_mtls_endpoint(None) is None + assert AlphaAnalyticsDataClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AlphaAnalyticsDataClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AlphaAnalyticsDataClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AlphaAnalyticsDataClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AlphaAnalyticsDataClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AlphaAnalyticsDataClient, "grpc"), + (AlphaAnalyticsDataAsyncClient, "grpc_asyncio"), + (AlphaAnalyticsDataClient, "rest"), +]) +def test_alpha_analytics_data_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 == ( + 'analyticsdata.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://analyticsdata.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AlphaAnalyticsDataGrpcTransport, "grpc"), + (transports.AlphaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AlphaAnalyticsDataRestTransport, "rest"), +]) +def test_alpha_analytics_data_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", [ + (AlphaAnalyticsDataClient, "grpc"), + (AlphaAnalyticsDataAsyncClient, "grpc_asyncio"), + (AlphaAnalyticsDataClient, "rest"), +]) +def test_alpha_analytics_data_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 == ( + 'analyticsdata.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://analyticsdata.googleapis.com' + ) + + +def test_alpha_analytics_data_client_get_transport_class(): + transport = AlphaAnalyticsDataClient.get_transport_class() + available_transports = [ + transports.AlphaAnalyticsDataGrpcTransport, + transports.AlphaAnalyticsDataRestTransport, + ] + assert transport in available_transports + + transport = AlphaAnalyticsDataClient.get_transport_class("grpc") + assert transport == transports.AlphaAnalyticsDataGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataGrpcTransport, "grpc"), + (AlphaAnalyticsDataAsyncClient, transports.AlphaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio"), + (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataRestTransport, "rest"), +]) +@mock.patch.object(AlphaAnalyticsDataClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlphaAnalyticsDataClient)) +@mock.patch.object(AlphaAnalyticsDataAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlphaAnalyticsDataAsyncClient)) +def test_alpha_analytics_data_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(AlphaAnalyticsDataClient, '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(AlphaAnalyticsDataClient, '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, + 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): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # 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, + 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, + 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", [ + (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataGrpcTransport, "grpc", "true"), + (AlphaAnalyticsDataAsyncClient, transports.AlphaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataGrpcTransport, "grpc", "false"), + (AlphaAnalyticsDataAsyncClient, transports.AlphaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataRestTransport, "rest", "true"), + (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataRestTransport, "rest", "false"), +]) +@mock.patch.object(AlphaAnalyticsDataClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlphaAnalyticsDataClient)) +@mock.patch.object(AlphaAnalyticsDataAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlphaAnalyticsDataAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_alpha_analytics_data_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 + 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 + 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, + 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", [ + AlphaAnalyticsDataClient, AlphaAnalyticsDataAsyncClient +]) +@mock.patch.object(AlphaAnalyticsDataClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlphaAnalyticsDataClient)) +@mock.patch.object(AlphaAnalyticsDataAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlphaAnalyticsDataAsyncClient)) +def test_alpha_analytics_data_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 + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataGrpcTransport, "grpc"), + (AlphaAnalyticsDataAsyncClient, transports.AlphaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio"), + (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataRestTransport, "rest"), +]) +def test_alpha_analytics_data_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, + 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", [ + (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataGrpcTransport, "grpc", grpc_helpers), + (AlphaAnalyticsDataAsyncClient, transports.AlphaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataRestTransport, "rest", None), +]) +def test_alpha_analytics_data_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, + 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_alpha_analytics_data_client_client_options_from_dict(): + with mock.patch('google.analytics.data_v1alpha.services.alpha_analytics_data.transports.AlphaAnalyticsDataGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AlphaAnalyticsDataClient( + 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", [ + (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataGrpcTransport, "grpc", grpc_helpers), + (AlphaAnalyticsDataAsyncClient, transports.AlphaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_alpha_analytics_data_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, + 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( + "analyticsdata.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/analytics', + 'https://www.googleapis.com/auth/analytics.readonly', +), + scopes=None, + default_host="analyticsdata.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_data_api.RunFunnelReportRequest, + dict, +]) +def test_run_funnel_report(request_type, transport: str = 'grpc'): + client = AlphaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_funnel_report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_data_api.RunFunnelReportResponse( + kind='kind_value', + ) + response = client.run_funnel_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] == analytics_data_api.RunFunnelReportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.RunFunnelReportResponse) + assert response.kind == 'kind_value' + + +def test_run_funnel_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 = AlphaAnalyticsDataClient( + credentials=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_funnel_report), + '__call__') as call: + client.run_funnel_report() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.RunFunnelReportRequest() + +@pytest.mark.asyncio +async def test_run_funnel_report_async(transport: str = 'grpc_asyncio', request_type=analytics_data_api.RunFunnelReportRequest): + client = AlphaAnalyticsDataAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_funnel_report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.RunFunnelReportResponse( + kind='kind_value', + )) + response = await client.run_funnel_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.RunFunnelReportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.RunFunnelReportResponse) + assert response.kind == 'kind_value' + + +@pytest.mark.asyncio +async def test_run_funnel_report_async_from_dict(): + await test_run_funnel_report_async(request_type=dict) + + +def test_run_funnel_report_field_headers(): + client = AlphaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_data_api.RunFunnelReportRequest() + + request.property = 'property_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_funnel_report), + '__call__') as call: + call.return_value = analytics_data_api.RunFunnelReportResponse() + client.run_funnel_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', + 'property=property_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_run_funnel_report_field_headers_async(): + client = AlphaAnalyticsDataAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_data_api.RunFunnelReportRequest() + + request.property = 'property_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_funnel_report), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.RunFunnelReportResponse()) + await client.run_funnel_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', + 'property=property_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + analytics_data_api.RunFunnelReportRequest, + dict, +]) +def test_run_funnel_report_rest(request_type): + client = AlphaAnalyticsDataClient( + 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_data_api.RunFunnelReportResponse( + kind='kind_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = analytics_data_api.RunFunnelReportResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.run_funnel_report(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.RunFunnelReportResponse) + assert response.kind == 'kind_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_run_funnel_report_rest_interceptors(null_interceptor): + transport = transports.AlphaAnalyticsDataRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlphaAnalyticsDataRestInterceptor(), + ) + client = AlphaAnalyticsDataClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlphaAnalyticsDataRestInterceptor, "post_run_funnel_report") as post, \ + mock.patch.object(transports.AlphaAnalyticsDataRestInterceptor, "pre_run_funnel_report") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_data_api.RunFunnelReportRequest.pb(analytics_data_api.RunFunnelReportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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_data_api.RunFunnelReportResponse.to_json(analytics_data_api.RunFunnelReportResponse()) + + request = analytics_data_api.RunFunnelReportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_data_api.RunFunnelReportResponse() + + client.run_funnel_report(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_run_funnel_report_rest_bad_request(transport: str = 'rest', request_type=analytics_data_api.RunFunnelReportRequest): + client = AlphaAnalyticsDataClient( + 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.run_funnel_report(request) + + +def test_run_funnel_report_rest_error(): + client = AlphaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AlphaAnalyticsDataGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AlphaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AlphaAnalyticsDataGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AlphaAnalyticsDataClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AlphaAnalyticsDataGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AlphaAnalyticsDataClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AlphaAnalyticsDataClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AlphaAnalyticsDataGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AlphaAnalyticsDataClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AlphaAnalyticsDataGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AlphaAnalyticsDataClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AlphaAnalyticsDataGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AlphaAnalyticsDataGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AlphaAnalyticsDataGrpcTransport, + transports.AlphaAnalyticsDataGrpcAsyncIOTransport, + transports.AlphaAnalyticsDataRestTransport, +]) +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 = AlphaAnalyticsDataClient.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 = AlphaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AlphaAnalyticsDataGrpcTransport, + ) + +def test_alpha_analytics_data_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AlphaAnalyticsDataTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_alpha_analytics_data_base_transport(): + # Instantiate the base transport. + with mock.patch('google.analytics.data_v1alpha.services.alpha_analytics_data.transports.AlphaAnalyticsDataTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AlphaAnalyticsDataTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'run_funnel_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_alpha_analytics_data_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.data_v1alpha.services.alpha_analytics_data.transports.AlphaAnalyticsDataTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AlphaAnalyticsDataTransport( + 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', + 'https://www.googleapis.com/auth/analytics.readonly', +), + quota_project_id="octopus", + ) + + +def test_alpha_analytics_data_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.data_v1alpha.services.alpha_analytics_data.transports.AlphaAnalyticsDataTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AlphaAnalyticsDataTransport() + adc.assert_called_once() + + +def test_alpha_analytics_data_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) + AlphaAnalyticsDataClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/analytics', + 'https://www.googleapis.com/auth/analytics.readonly', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AlphaAnalyticsDataGrpcTransport, + transports.AlphaAnalyticsDataGrpcAsyncIOTransport, + ], +) +def test_alpha_analytics_data_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', 'https://www.googleapis.com/auth/analytics.readonly',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AlphaAnalyticsDataGrpcTransport, + transports.AlphaAnalyticsDataGrpcAsyncIOTransport, + transports.AlphaAnalyticsDataRestTransport, + ], +) +def test_alpha_analytics_data_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.AlphaAnalyticsDataGrpcTransport, grpc_helpers), + (transports.AlphaAnalyticsDataGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_alpha_analytics_data_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( + "analyticsdata.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/analytics', + 'https://www.googleapis.com/auth/analytics.readonly', +), + scopes=["1", "2"], + default_host="analyticsdata.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AlphaAnalyticsDataGrpcTransport, transports.AlphaAnalyticsDataGrpcAsyncIOTransport]) +def test_alpha_analytics_data_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_alpha_analytics_data_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.AlphaAnalyticsDataRestTransport ( + 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_alpha_analytics_data_host_no_port(transport_name): + client = AlphaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='analyticsdata.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'analyticsdata.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://analyticsdata.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_alpha_analytics_data_host_with_port(transport_name): + client = AlphaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='analyticsdata.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'analyticsdata.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://analyticsdata.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_alpha_analytics_data_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AlphaAnalyticsDataClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AlphaAnalyticsDataClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.run_funnel_report._session + session2 = client2.transport.run_funnel_report._session + assert session1 != session2 +def test_alpha_analytics_data_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AlphaAnalyticsDataGrpcTransport( + 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_alpha_analytics_data_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AlphaAnalyticsDataGrpcAsyncIOTransport( + 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.AlphaAnalyticsDataGrpcTransport, transports.AlphaAnalyticsDataGrpcAsyncIOTransport]) +def test_alpha_analytics_data_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.AlphaAnalyticsDataGrpcTransport, transports.AlphaAnalyticsDataGrpcAsyncIOTransport]) +def test_alpha_analytics_data_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_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AlphaAnalyticsDataClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = AlphaAnalyticsDataClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AlphaAnalyticsDataClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = AlphaAnalyticsDataClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = AlphaAnalyticsDataClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AlphaAnalyticsDataClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AlphaAnalyticsDataClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = AlphaAnalyticsDataClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AlphaAnalyticsDataClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = AlphaAnalyticsDataClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = AlphaAnalyticsDataClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AlphaAnalyticsDataClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AlphaAnalyticsDataClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = AlphaAnalyticsDataClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AlphaAnalyticsDataClient.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.AlphaAnalyticsDataTransport, '_prep_wrapped_messages') as prep: + client = AlphaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AlphaAnalyticsDataTransport, '_prep_wrapped_messages') as prep: + transport_class = AlphaAnalyticsDataClient.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 = AlphaAnalyticsDataAsyncClient( + 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 = AlphaAnalyticsDataClient( + 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 = AlphaAnalyticsDataClient( + 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", [ + (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataGrpcTransport), + (AlphaAnalyticsDataAsyncClient, transports.AlphaAnalyticsDataGrpcAsyncIOTransport), +]) +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, + 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/v1beta/.coveragerc b/owl-bot-staging/v1beta/.coveragerc new file mode 100644 index 0000000..535122d --- /dev/null +++ b/owl-bot-staging/v1beta/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/analytics/data/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1beta/.flake8 b/owl-bot-staging/v1beta/.flake8 new file mode 100644 index 0000000..29227d4 --- /dev/null +++ b/owl-bot-staging/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/v1beta/MANIFEST.in b/owl-bot-staging/v1beta/MANIFEST.in new file mode 100644 index 0000000..910ea96 --- /dev/null +++ b/owl-bot-staging/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/analytics/data *.py +recursive-include google/analytics/data_v1beta *.py diff --git a/owl-bot-staging/v1beta/README.rst b/owl-bot-staging/v1beta/README.rst new file mode 100644 index 0000000..d62497b --- /dev/null +++ b/owl-bot-staging/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Analytics Data 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 Data 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/v1beta/docs/conf.py b/owl-bot-staging/v1beta/docs/conf.py new file mode 100644 index 0000000..ad79bba --- /dev/null +++ b/owl-bot-staging/v1beta/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-data 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-data" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google 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-data-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-data.tex", + u"google-analytics-data 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-data", + u"Google Analytics Data 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-data", + u"google-analytics-data Documentation", + author, + "google-analytics-data", + "GAPIC library for Google Analytics Data 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/v1beta/docs/data_v1beta/beta_analytics_data.rst b/owl-bot-staging/v1beta/docs/data_v1beta/beta_analytics_data.rst new file mode 100644 index 0000000..7bcaa51 --- /dev/null +++ b/owl-bot-staging/v1beta/docs/data_v1beta/beta_analytics_data.rst @@ -0,0 +1,6 @@ +BetaAnalyticsData +----------------------------------- + +.. automodule:: google.analytics.data_v1beta.services.beta_analytics_data + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta/docs/data_v1beta/services.rst b/owl-bot-staging/v1beta/docs/data_v1beta/services.rst new file mode 100644 index 0000000..769b3f8 --- /dev/null +++ b/owl-bot-staging/v1beta/docs/data_v1beta/services.rst @@ -0,0 +1,6 @@ +Services for Google Analytics Data v1beta API +============================================= +.. toctree:: + :maxdepth: 2 + + beta_analytics_data diff --git a/owl-bot-staging/v1beta/docs/data_v1beta/types.rst b/owl-bot-staging/v1beta/docs/data_v1beta/types.rst new file mode 100644 index 0000000..e7db7e0 --- /dev/null +++ b/owl-bot-staging/v1beta/docs/data_v1beta/types.rst @@ -0,0 +1,7 @@ +Types for Google Analytics Data v1beta API +========================================== + +.. automodule:: google.analytics.data_v1beta.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1beta/docs/index.rst b/owl-bot-staging/v1beta/docs/index.rst new file mode 100644 index 0000000..aa46cf2 --- /dev/null +++ b/owl-bot-staging/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + data_v1beta/services + data_v1beta/types diff --git a/owl-bot-staging/v1beta/google/analytics/data/__init__.py b/owl-bot-staging/v1beta/google/analytics/data/__init__.py new file mode 100644 index 0000000..6343a3b --- /dev/null +++ b/owl-bot-staging/v1beta/google/analytics/data/__init__.py @@ -0,0 +1,121 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.data import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.analytics.data_v1beta.services.beta_analytics_data.client import BetaAnalyticsDataClient +from google.analytics.data_v1beta.services.beta_analytics_data.async_client import BetaAnalyticsDataAsyncClient + +from google.analytics.data_v1beta.types.analytics_data_api import BatchRunPivotReportsRequest +from google.analytics.data_v1beta.types.analytics_data_api import BatchRunPivotReportsResponse +from google.analytics.data_v1beta.types.analytics_data_api import BatchRunReportsRequest +from google.analytics.data_v1beta.types.analytics_data_api import BatchRunReportsResponse +from google.analytics.data_v1beta.types.analytics_data_api import CheckCompatibilityRequest +from google.analytics.data_v1beta.types.analytics_data_api import CheckCompatibilityResponse +from google.analytics.data_v1beta.types.analytics_data_api import GetMetadataRequest +from google.analytics.data_v1beta.types.analytics_data_api import Metadata +from google.analytics.data_v1beta.types.analytics_data_api import RunPivotReportRequest +from google.analytics.data_v1beta.types.analytics_data_api import RunPivotReportResponse +from google.analytics.data_v1beta.types.analytics_data_api import RunRealtimeReportRequest +from google.analytics.data_v1beta.types.analytics_data_api import RunRealtimeReportResponse +from google.analytics.data_v1beta.types.analytics_data_api import RunReportRequest +from google.analytics.data_v1beta.types.analytics_data_api import RunReportResponse +from google.analytics.data_v1beta.types.data import Cohort +from google.analytics.data_v1beta.types.data import CohortReportSettings +from google.analytics.data_v1beta.types.data import CohortSpec +from google.analytics.data_v1beta.types.data import CohortsRange +from google.analytics.data_v1beta.types.data import DateRange +from google.analytics.data_v1beta.types.data import Dimension +from google.analytics.data_v1beta.types.data import DimensionCompatibility +from google.analytics.data_v1beta.types.data import DimensionExpression +from google.analytics.data_v1beta.types.data import DimensionHeader +from google.analytics.data_v1beta.types.data import DimensionMetadata +from google.analytics.data_v1beta.types.data import DimensionValue +from google.analytics.data_v1beta.types.data import Filter +from google.analytics.data_v1beta.types.data import FilterExpression +from google.analytics.data_v1beta.types.data import FilterExpressionList +from google.analytics.data_v1beta.types.data import Metric +from google.analytics.data_v1beta.types.data import MetricCompatibility +from google.analytics.data_v1beta.types.data import MetricHeader +from google.analytics.data_v1beta.types.data import MetricMetadata +from google.analytics.data_v1beta.types.data import MetricValue +from google.analytics.data_v1beta.types.data import MinuteRange +from google.analytics.data_v1beta.types.data import NumericValue +from google.analytics.data_v1beta.types.data import OrderBy +from google.analytics.data_v1beta.types.data import Pivot +from google.analytics.data_v1beta.types.data import PivotDimensionHeader +from google.analytics.data_v1beta.types.data import PivotHeader +from google.analytics.data_v1beta.types.data import PropertyQuota +from google.analytics.data_v1beta.types.data import QuotaStatus +from google.analytics.data_v1beta.types.data import ResponseMetaData +from google.analytics.data_v1beta.types.data import Row +from google.analytics.data_v1beta.types.data import Compatibility +from google.analytics.data_v1beta.types.data import MetricAggregation +from google.analytics.data_v1beta.types.data import MetricType +from google.analytics.data_v1beta.types.data import RestrictedMetricType + +__all__ = ('BetaAnalyticsDataClient', + 'BetaAnalyticsDataAsyncClient', + 'BatchRunPivotReportsRequest', + 'BatchRunPivotReportsResponse', + 'BatchRunReportsRequest', + 'BatchRunReportsResponse', + 'CheckCompatibilityRequest', + 'CheckCompatibilityResponse', + 'GetMetadataRequest', + 'Metadata', + 'RunPivotReportRequest', + 'RunPivotReportResponse', + 'RunRealtimeReportRequest', + 'RunRealtimeReportResponse', + 'RunReportRequest', + 'RunReportResponse', + 'Cohort', + 'CohortReportSettings', + 'CohortSpec', + 'CohortsRange', + 'DateRange', + 'Dimension', + 'DimensionCompatibility', + 'DimensionExpression', + 'DimensionHeader', + 'DimensionMetadata', + 'DimensionValue', + 'Filter', + 'FilterExpression', + 'FilterExpressionList', + 'Metric', + 'MetricCompatibility', + 'MetricHeader', + 'MetricMetadata', + 'MetricValue', + 'MinuteRange', + 'NumericValue', + 'OrderBy', + 'Pivot', + 'PivotDimensionHeader', + 'PivotHeader', + 'PropertyQuota', + 'QuotaStatus', + 'ResponseMetaData', + 'Row', + 'Compatibility', + 'MetricAggregation', + 'MetricType', + 'RestrictedMetricType', +) diff --git a/owl-bot-staging/v1beta/google/analytics/data/gapic_version.py b/owl-bot-staging/v1beta/google/analytics/data/gapic_version.py new file mode 100644 index 0000000..35859c3 --- /dev/null +++ b/owl-bot-staging/v1beta/google/analytics/data/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.1.0" diff --git a/owl-bot-staging/v1beta/google/analytics/data/py.typed b/owl-bot-staging/v1beta/google/analytics/data/py.typed new file mode 100644 index 0000000..1d549e5 --- /dev/null +++ b/owl-bot-staging/v1beta/google/analytics/data/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-analytics-data package uses inline types. diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/__init__.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/__init__.py new file mode 100644 index 0000000..ad2bbe9 --- /dev/null +++ b/owl-bot-staging/v1beta/google/analytics/data_v1beta/__init__.py @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.data import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.beta_analytics_data import BetaAnalyticsDataClient +from .services.beta_analytics_data import BetaAnalyticsDataAsyncClient + +from .types.analytics_data_api import BatchRunPivotReportsRequest +from .types.analytics_data_api import BatchRunPivotReportsResponse +from .types.analytics_data_api import BatchRunReportsRequest +from .types.analytics_data_api import BatchRunReportsResponse +from .types.analytics_data_api import CheckCompatibilityRequest +from .types.analytics_data_api import CheckCompatibilityResponse +from .types.analytics_data_api import GetMetadataRequest +from .types.analytics_data_api import Metadata +from .types.analytics_data_api import RunPivotReportRequest +from .types.analytics_data_api import RunPivotReportResponse +from .types.analytics_data_api import RunRealtimeReportRequest +from .types.analytics_data_api import RunRealtimeReportResponse +from .types.analytics_data_api import RunReportRequest +from .types.analytics_data_api import RunReportResponse +from .types.data import Cohort +from .types.data import CohortReportSettings +from .types.data import CohortSpec +from .types.data import CohortsRange +from .types.data import DateRange +from .types.data import Dimension +from .types.data import DimensionCompatibility +from .types.data import DimensionExpression +from .types.data import DimensionHeader +from .types.data import DimensionMetadata +from .types.data import DimensionValue +from .types.data import Filter +from .types.data import FilterExpression +from .types.data import FilterExpressionList +from .types.data import Metric +from .types.data import MetricCompatibility +from .types.data import MetricHeader +from .types.data import MetricMetadata +from .types.data import MetricValue +from .types.data import MinuteRange +from .types.data import NumericValue +from .types.data import OrderBy +from .types.data import Pivot +from .types.data import PivotDimensionHeader +from .types.data import PivotHeader +from .types.data import PropertyQuota +from .types.data import QuotaStatus +from .types.data import ResponseMetaData +from .types.data import Row +from .types.data import Compatibility +from .types.data import MetricAggregation +from .types.data import MetricType +from .types.data import RestrictedMetricType + +__all__ = ( + 'BetaAnalyticsDataAsyncClient', +'BatchRunPivotReportsRequest', +'BatchRunPivotReportsResponse', +'BatchRunReportsRequest', +'BatchRunReportsResponse', +'BetaAnalyticsDataClient', +'CheckCompatibilityRequest', +'CheckCompatibilityResponse', +'Cohort', +'CohortReportSettings', +'CohortSpec', +'CohortsRange', +'Compatibility', +'DateRange', +'Dimension', +'DimensionCompatibility', +'DimensionExpression', +'DimensionHeader', +'DimensionMetadata', +'DimensionValue', +'Filter', +'FilterExpression', +'FilterExpressionList', +'GetMetadataRequest', +'Metadata', +'Metric', +'MetricAggregation', +'MetricCompatibility', +'MetricHeader', +'MetricMetadata', +'MetricType', +'MetricValue', +'MinuteRange', +'NumericValue', +'OrderBy', +'Pivot', +'PivotDimensionHeader', +'PivotHeader', +'PropertyQuota', +'QuotaStatus', +'ResponseMetaData', +'RestrictedMetricType', +'Row', +'RunPivotReportRequest', +'RunPivotReportResponse', +'RunRealtimeReportRequest', +'RunRealtimeReportResponse', +'RunReportRequest', +'RunReportResponse', +) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/gapic_metadata.json b/owl-bot-staging/v1beta/google/analytics/data_v1beta/gapic_metadata.json new file mode 100644 index 0000000..e1e3750 --- /dev/null +++ b/owl-bot-staging/v1beta/google/analytics/data_v1beta/gapic_metadata.json @@ -0,0 +1,133 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.analytics.data_v1beta", + "protoPackage": "google.analytics.data.v1beta", + "schema": "1.0", + "services": { + "BetaAnalyticsData": { + "clients": { + "grpc": { + "libraryClient": "BetaAnalyticsDataClient", + "rpcs": { + "BatchRunPivotReports": { + "methods": [ + "batch_run_pivot_reports" + ] + }, + "BatchRunReports": { + "methods": [ + "batch_run_reports" + ] + }, + "CheckCompatibility": { + "methods": [ + "check_compatibility" + ] + }, + "GetMetadata": { + "methods": [ + "get_metadata" + ] + }, + "RunPivotReport": { + "methods": [ + "run_pivot_report" + ] + }, + "RunRealtimeReport": { + "methods": [ + "run_realtime_report" + ] + }, + "RunReport": { + "methods": [ + "run_report" + ] + } + } + }, + "grpc-async": { + "libraryClient": "BetaAnalyticsDataAsyncClient", + "rpcs": { + "BatchRunPivotReports": { + "methods": [ + "batch_run_pivot_reports" + ] + }, + "BatchRunReports": { + "methods": [ + "batch_run_reports" + ] + }, + "CheckCompatibility": { + "methods": [ + "check_compatibility" + ] + }, + "GetMetadata": { + "methods": [ + "get_metadata" + ] + }, + "RunPivotReport": { + "methods": [ + "run_pivot_report" + ] + }, + "RunRealtimeReport": { + "methods": [ + "run_realtime_report" + ] + }, + "RunReport": { + "methods": [ + "run_report" + ] + } + } + }, + "rest": { + "libraryClient": "BetaAnalyticsDataClient", + "rpcs": { + "BatchRunPivotReports": { + "methods": [ + "batch_run_pivot_reports" + ] + }, + "BatchRunReports": { + "methods": [ + "batch_run_reports" + ] + }, + "CheckCompatibility": { + "methods": [ + "check_compatibility" + ] + }, + "GetMetadata": { + "methods": [ + "get_metadata" + ] + }, + "RunPivotReport": { + "methods": [ + "run_pivot_report" + ] + }, + "RunRealtimeReport": { + "methods": [ + "run_realtime_report" + ] + }, + "RunReport": { + "methods": [ + "run_report" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/py.typed b/owl-bot-staging/v1beta/google/analytics/data_v1beta/py.typed new file mode 100644 index 0000000..1d549e5 --- /dev/null +++ b/owl-bot-staging/v1beta/google/analytics/data_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-analytics-data package uses inline types. diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/__init__.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/__init__.py new file mode 100644 index 0000000..e8e1c38 --- /dev/null +++ b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/__init__.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/__init__.py new file mode 100644 index 0000000..da34317 --- /dev/null +++ b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 BetaAnalyticsDataClient +from .async_client import BetaAnalyticsDataAsyncClient + +__all__ = ( + 'BetaAnalyticsDataClient', + 'BetaAnalyticsDataAsyncClient', +) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/async_client.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/async_client.py new file mode 100644 index 0000000..287b324 --- /dev/null +++ b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/async_client.py @@ -0,0 +1,846 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.analytics.data_v1beta.types import analytics_data_api +from google.analytics.data_v1beta.types import data +from .transports.base import BetaAnalyticsDataTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import BetaAnalyticsDataGrpcAsyncIOTransport +from .client import BetaAnalyticsDataClient + + +class BetaAnalyticsDataAsyncClient: + """Google Analytics reporting data service.""" + + _client: BetaAnalyticsDataClient + + DEFAULT_ENDPOINT = BetaAnalyticsDataClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = BetaAnalyticsDataClient.DEFAULT_MTLS_ENDPOINT + + metadata_path = staticmethod(BetaAnalyticsDataClient.metadata_path) + parse_metadata_path = staticmethod(BetaAnalyticsDataClient.parse_metadata_path) + common_billing_account_path = staticmethod(BetaAnalyticsDataClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(BetaAnalyticsDataClient.parse_common_billing_account_path) + common_folder_path = staticmethod(BetaAnalyticsDataClient.common_folder_path) + parse_common_folder_path = staticmethod(BetaAnalyticsDataClient.parse_common_folder_path) + common_organization_path = staticmethod(BetaAnalyticsDataClient.common_organization_path) + parse_common_organization_path = staticmethod(BetaAnalyticsDataClient.parse_common_organization_path) + common_project_path = staticmethod(BetaAnalyticsDataClient.common_project_path) + parse_common_project_path = staticmethod(BetaAnalyticsDataClient.parse_common_project_path) + common_location_path = staticmethod(BetaAnalyticsDataClient.common_location_path) + parse_common_location_path = staticmethod(BetaAnalyticsDataClient.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: + BetaAnalyticsDataAsyncClient: The constructed client. + """ + return BetaAnalyticsDataClient.from_service_account_info.__func__(BetaAnalyticsDataAsyncClient, 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: + BetaAnalyticsDataAsyncClient: The constructed client. + """ + return BetaAnalyticsDataClient.from_service_account_file.__func__(BetaAnalyticsDataAsyncClient, 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 variabel 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 BetaAnalyticsDataClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> BetaAnalyticsDataTransport: + """Returns the transport used by the client instance. + + Returns: + BetaAnalyticsDataTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(BetaAnalyticsDataClient).get_transport_class, type(BetaAnalyticsDataClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, BetaAnalyticsDataTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the beta analytics data client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.BetaAnalyticsDataTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = BetaAnalyticsDataClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def run_report(self, + request: Optional[Union[analytics_data_api.RunReportRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.RunReportResponse: + r"""Returns a customized report of your Google Analytics event data. + Reports contain statistics derived from data collected by the + Google Analytics tracking code. The data returned from the API + is as a table with columns for the requested dimensions and + metrics. Metrics are individual measurements of user activity on + your property, such as active users or event count. Dimensions + break down metrics across some common criteria, such as country + or event name. + + For a guide to constructing requests & understanding responses, + see `Creating a + Report `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 data_v1beta + + async def sample_run_report(): + # Create a client + client = data_v1beta.BetaAnalyticsDataAsyncClient() + + # Initialize request argument(s) + request = data_v1beta.RunReportRequest( + ) + + # Make the request + response = await client.run_report(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.data_v1beta.types.RunReportRequest, dict]]): + The request object. The request to generate a 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.data_v1beta.types.RunReportResponse: + The response report table + corresponding to a request. + + """ + # Create or coerce a protobuf request object. + request = analytics_data_api.RunReportRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.run_report, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("property", request.property), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_pivot_report(self, + request: Optional[Union[analytics_data_api.RunPivotReportRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.RunPivotReportResponse: + r"""Returns a customized pivot report of your Google + Analytics event data. Pivot reports are more advanced + and expressive formats than regular reports. In a pivot + report, dimensions are only visible if they are included + in a pivot. Multiple pivots can be specified to further + dissect your data. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import data_v1beta + + async def sample_run_pivot_report(): + # Create a client + client = data_v1beta.BetaAnalyticsDataAsyncClient() + + # Initialize request argument(s) + request = data_v1beta.RunPivotReportRequest( + ) + + # Make the request + response = await client.run_pivot_report(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.data_v1beta.types.RunPivotReportRequest, dict]]): + The request object. The request to generate a pivot + 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.data_v1beta.types.RunPivotReportResponse: + The response pivot report table + corresponding to a pivot request. + + """ + # Create or coerce a protobuf request object. + request = analytics_data_api.RunPivotReportRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.run_pivot_report, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("property", request.property), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_run_reports(self, + request: Optional[Union[analytics_data_api.BatchRunReportsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.BatchRunReportsResponse: + r"""Returns multiple reports in a batch. All reports must + be for the same 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 data_v1beta + + async def sample_batch_run_reports(): + # Create a client + client = data_v1beta.BetaAnalyticsDataAsyncClient() + + # Initialize request argument(s) + request = data_v1beta.BatchRunReportsRequest( + ) + + # Make the request + response = await client.batch_run_reports(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.data_v1beta.types.BatchRunReportsRequest, dict]]): + The request object. The batch request containing + multiple report requests. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.data_v1beta.types.BatchRunReportsResponse: + The batch response containing + multiple reports. + + """ + # Create or coerce a protobuf request object. + request = analytics_data_api.BatchRunReportsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_run_reports, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("property", request.property), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_run_pivot_reports(self, + request: Optional[Union[analytics_data_api.BatchRunPivotReportsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.BatchRunPivotReportsResponse: + r"""Returns multiple pivot reports in a batch. All + reports must be for the same 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 data_v1beta + + async def sample_batch_run_pivot_reports(): + # Create a client + client = data_v1beta.BetaAnalyticsDataAsyncClient() + + # Initialize request argument(s) + request = data_v1beta.BatchRunPivotReportsRequest( + ) + + # Make the request + response = await client.batch_run_pivot_reports(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.data_v1beta.types.BatchRunPivotReportsRequest, dict]]): + The request object. The batch request containing + multiple pivot report requests. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.data_v1beta.types.BatchRunPivotReportsResponse: + The batch response containing + multiple pivot reports. + + """ + # Create or coerce a protobuf request object. + request = analytics_data_api.BatchRunPivotReportsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_run_pivot_reports, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("property", request.property), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_metadata(self, + request: Optional[Union[analytics_data_api.GetMetadataRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.Metadata: + r"""Returns metadata for dimensions and metrics available in + reporting methods. Used to explore the dimensions and metrics. + In this method, a Google Analytics GA4 Property Identifier is + specified in the request, and the metadata response includes + Custom dimensions and metrics as well as Universal metadata. + + For example if a custom metric with parameter name + ``levels_unlocked`` is registered to a property, the Metadata + response will contain ``customEvent:levels_unlocked``. Universal + metadata are dimensions and metrics applicable to any property + such as ``country`` and ``totalUsers``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 data_v1beta + + async def sample_get_metadata(): + # Create a client + client = data_v1beta.BetaAnalyticsDataAsyncClient() + + # Initialize request argument(s) + request = data_v1beta.GetMetadataRequest( + name="name_value", + ) + + # Make the request + response = await client.get_metadata(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.data_v1beta.types.GetMetadataRequest, dict]]): + The request object. Request for a property's dimension + and metric metadata. + name (:class:`str`): + Required. The resource name of the metadata to retrieve. + This name field is specified in the URL path and not URL + parameters. Property is a numeric Google Analytics GA4 + Property identifier. To learn more, see `where to find + your Property + ID `__. + + Example: properties/1234/metadata + + Set the Property ID to 0 for dimensions and metrics + common to all properties. In this special mode, this + method will not return custom dimensions and metrics. + + 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.data_v1beta.types.Metadata: + The dimensions and metrics currently + accepted in reporting methods. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = analytics_data_api.GetMetadataRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_metadata, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_realtime_report(self, + request: Optional[Union[analytics_data_api.RunRealtimeReportRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.RunRealtimeReportResponse: + r"""Returns a customized report of realtime event data for your + property. Events appear in realtime reports seconds after they + have been sent to the Google Analytics. Realtime reports show + events and usage data for the periods of time ranging from the + present moment to 30 minutes ago (up to 60 minutes for Google + Analytics 360 properties). + + For a guide to constructing realtime requests & understanding + responses, see `Creating a Realtime + Report `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 data_v1beta + + async def sample_run_realtime_report(): + # Create a client + client = data_v1beta.BetaAnalyticsDataAsyncClient() + + # Initialize request argument(s) + request = data_v1beta.RunRealtimeReportRequest( + ) + + # Make the request + response = await client.run_realtime_report(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.data_v1beta.types.RunRealtimeReportRequest, dict]]): + The request object. The request to generate a realtime + 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.data_v1beta.types.RunRealtimeReportResponse: + The response realtime report table + corresponding to a request. + + """ + # Create or coerce a protobuf request object. + request = analytics_data_api.RunRealtimeReportRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.run_realtime_report, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("property", request.property), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def check_compatibility(self, + request: Optional[Union[analytics_data_api.CheckCompatibilityRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.CheckCompatibilityResponse: + r"""This compatibility method lists dimensions and + metrics that can be added to a report request and + maintain compatibility. This method fails if the + request's dimensions and metrics are incompatible. + In Google Analytics, reports fail if they request + incompatible dimensions and/or metrics; in that case, + you will need to remove dimensions and/or metrics from + the incompatible report until the report is compatible. + The Realtime and Core reports have different + compatibility rules. This method checks compatibility + for Core reports. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 data_v1beta + + async def sample_check_compatibility(): + # Create a client + client = data_v1beta.BetaAnalyticsDataAsyncClient() + + # Initialize request argument(s) + request = data_v1beta.CheckCompatibilityRequest( + ) + + # Make the request + response = await client.check_compatibility(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.data_v1beta.types.CheckCompatibilityRequest, dict]]): + The request object. The request for compatibility + information for a report's dimensions and metrics. Check + compatibility provides a preview of the compatibility of + a report; fields shared with the `runReport` request + should be the same values as in your `runReport` + request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.data_v1beta.types.CheckCompatibilityResponse: + The compatibility response with the + compatibility of each dimension & + metric. + + """ + # Create or coerce a protobuf request object. + request = analytics_data_api.CheckCompatibilityRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.check_compatibility, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("property", request.property), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-analytics-data", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "BetaAnalyticsDataAsyncClient", +) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/client.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/client.py new file mode 100644 index 0000000..233a1b8 --- /dev/null +++ b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/client.py @@ -0,0 +1,1058 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.analytics.data_v1beta.types import analytics_data_api +from google.analytics.data_v1beta.types import data +from .transports.base import BetaAnalyticsDataTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import BetaAnalyticsDataGrpcTransport +from .transports.grpc_asyncio import BetaAnalyticsDataGrpcAsyncIOTransport +from .transports.rest import BetaAnalyticsDataRestTransport + + +class BetaAnalyticsDataClientMeta(type): + """Metaclass for the BetaAnalyticsData 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[BetaAnalyticsDataTransport]] + _transport_registry["grpc"] = BetaAnalyticsDataGrpcTransport + _transport_registry["grpc_asyncio"] = BetaAnalyticsDataGrpcAsyncIOTransport + _transport_registry["rest"] = BetaAnalyticsDataRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[BetaAnalyticsDataTransport]: + """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 BetaAnalyticsDataClient(metaclass=BetaAnalyticsDataClientMeta): + """Google Analytics reporting data service.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "analyticsdata.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + BetaAnalyticsDataClient: 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: + BetaAnalyticsDataClient: 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) -> BetaAnalyticsDataTransport: + """Returns the transport used by the client instance. + + Returns: + BetaAnalyticsDataTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def metadata_path(property: str,) -> str: + """Returns a fully-qualified metadata string.""" + return "properties/{property}/metadata".format(property=property, ) + + @staticmethod + def parse_metadata_path(path: str) -> Dict[str,str]: + """Parses a metadata path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/metadata$", 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): + """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 variabel 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. + """ + 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 + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, BetaAnalyticsDataTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the beta analytics data client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, BetaAnalyticsDataTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(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. + if isinstance(transport, BetaAnalyticsDataTransport): + # transport is a BetaAnalyticsDataTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def run_report(self, + request: Optional[Union[analytics_data_api.RunReportRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.RunReportResponse: + r"""Returns a customized report of your Google Analytics event data. + Reports contain statistics derived from data collected by the + Google Analytics tracking code. The data returned from the API + is as a table with columns for the requested dimensions and + metrics. Metrics are individual measurements of user activity on + your property, such as active users or event count. Dimensions + break down metrics across some common criteria, such as country + or event name. + + For a guide to constructing requests & understanding responses, + see `Creating a + Report `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 data_v1beta + + def sample_run_report(): + # Create a client + client = data_v1beta.BetaAnalyticsDataClient() + + # Initialize request argument(s) + request = data_v1beta.RunReportRequest( + ) + + # Make the request + response = client.run_report(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.data_v1beta.types.RunReportRequest, dict]): + The request object. The request to generate a 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.data_v1beta.types.RunReportResponse: + The response report table + corresponding to a request. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a analytics_data_api.RunReportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, analytics_data_api.RunReportRequest): + request = analytics_data_api.RunReportRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.run_report] + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def run_pivot_report(self, + request: Optional[Union[analytics_data_api.RunPivotReportRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.RunPivotReportResponse: + r"""Returns a customized pivot report of your Google + Analytics event data. Pivot reports are more advanced + and expressive formats than regular reports. In a pivot + report, dimensions are only visible if they are included + in a pivot. Multiple pivots can be specified to further + dissect your data. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import data_v1beta + + def sample_run_pivot_report(): + # Create a client + client = data_v1beta.BetaAnalyticsDataClient() + + # Initialize request argument(s) + request = data_v1beta.RunPivotReportRequest( + ) + + # Make the request + response = client.run_pivot_report(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.data_v1beta.types.RunPivotReportRequest, dict]): + The request object. The request to generate a pivot + 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.data_v1beta.types.RunPivotReportResponse: + The response pivot report table + corresponding to a pivot request. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a analytics_data_api.RunPivotReportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, analytics_data_api.RunPivotReportRequest): + request = analytics_data_api.RunPivotReportRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.run_pivot_report] + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_run_reports(self, + request: Optional[Union[analytics_data_api.BatchRunReportsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.BatchRunReportsResponse: + r"""Returns multiple reports in a batch. All reports must + be for the same 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 data_v1beta + + def sample_batch_run_reports(): + # Create a client + client = data_v1beta.BetaAnalyticsDataClient() + + # Initialize request argument(s) + request = data_v1beta.BatchRunReportsRequest( + ) + + # Make the request + response = client.batch_run_reports(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.data_v1beta.types.BatchRunReportsRequest, dict]): + The request object. The batch request containing + multiple report requests. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.data_v1beta.types.BatchRunReportsResponse: + The batch response containing + multiple reports. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a analytics_data_api.BatchRunReportsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, analytics_data_api.BatchRunReportsRequest): + request = analytics_data_api.BatchRunReportsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_run_reports] + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_run_pivot_reports(self, + request: Optional[Union[analytics_data_api.BatchRunPivotReportsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.BatchRunPivotReportsResponse: + r"""Returns multiple pivot reports in a batch. All + reports must be for the same 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 data_v1beta + + def sample_batch_run_pivot_reports(): + # Create a client + client = data_v1beta.BetaAnalyticsDataClient() + + # Initialize request argument(s) + request = data_v1beta.BatchRunPivotReportsRequest( + ) + + # Make the request + response = client.batch_run_pivot_reports(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.data_v1beta.types.BatchRunPivotReportsRequest, dict]): + The request object. The batch request containing + multiple pivot report requests. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.data_v1beta.types.BatchRunPivotReportsResponse: + The batch response containing + multiple pivot reports. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a analytics_data_api.BatchRunPivotReportsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, analytics_data_api.BatchRunPivotReportsRequest): + request = analytics_data_api.BatchRunPivotReportsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_run_pivot_reports] + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_metadata(self, + request: Optional[Union[analytics_data_api.GetMetadataRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.Metadata: + r"""Returns metadata for dimensions and metrics available in + reporting methods. Used to explore the dimensions and metrics. + In this method, a Google Analytics GA4 Property Identifier is + specified in the request, and the metadata response includes + Custom dimensions and metrics as well as Universal metadata. + + For example if a custom metric with parameter name + ``levels_unlocked`` is registered to a property, the Metadata + response will contain ``customEvent:levels_unlocked``. Universal + metadata are dimensions and metrics applicable to any property + such as ``country`` and ``totalUsers``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 data_v1beta + + def sample_get_metadata(): + # Create a client + client = data_v1beta.BetaAnalyticsDataClient() + + # Initialize request argument(s) + request = data_v1beta.GetMetadataRequest( + name="name_value", + ) + + # Make the request + response = client.get_metadata(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.data_v1beta.types.GetMetadataRequest, dict]): + The request object. Request for a property's dimension + and metric metadata. + name (str): + Required. The resource name of the metadata to retrieve. + This name field is specified in the URL path and not URL + parameters. Property is a numeric Google Analytics GA4 + Property identifier. To learn more, see `where to find + your Property + ID `__. + + Example: properties/1234/metadata + + Set the Property ID to 0 for dimensions and metrics + common to all properties. In this special mode, this + method will not return custom dimensions and metrics. + + 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.data_v1beta.types.Metadata: + The dimensions and metrics currently + accepted in reporting methods. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a analytics_data_api.GetMetadataRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, analytics_data_api.GetMetadataRequest): + request = analytics_data_api.GetMetadataRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_metadata] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def run_realtime_report(self, + request: Optional[Union[analytics_data_api.RunRealtimeReportRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.RunRealtimeReportResponse: + r"""Returns a customized report of realtime event data for your + property. Events appear in realtime reports seconds after they + have been sent to the Google Analytics. Realtime reports show + events and usage data for the periods of time ranging from the + present moment to 30 minutes ago (up to 60 minutes for Google + Analytics 360 properties). + + For a guide to constructing realtime requests & understanding + responses, see `Creating a Realtime + Report `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 data_v1beta + + def sample_run_realtime_report(): + # Create a client + client = data_v1beta.BetaAnalyticsDataClient() + + # Initialize request argument(s) + request = data_v1beta.RunRealtimeReportRequest( + ) + + # Make the request + response = client.run_realtime_report(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.data_v1beta.types.RunRealtimeReportRequest, dict]): + The request object. The request to generate a realtime + 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.data_v1beta.types.RunRealtimeReportResponse: + The response realtime report table + corresponding to a request. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a analytics_data_api.RunRealtimeReportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, analytics_data_api.RunRealtimeReportRequest): + request = analytics_data_api.RunRealtimeReportRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.run_realtime_report] + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def check_compatibility(self, + request: Optional[Union[analytics_data_api.CheckCompatibilityRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.CheckCompatibilityResponse: + r"""This compatibility method lists dimensions and + metrics that can be added to a report request and + maintain compatibility. This method fails if the + request's dimensions and metrics are incompatible. + In Google Analytics, reports fail if they request + incompatible dimensions and/or metrics; in that case, + you will need to remove dimensions and/or metrics from + the incompatible report until the report is compatible. + The Realtime and Core reports have different + compatibility rules. This method checks compatibility + for Core reports. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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 data_v1beta + + def sample_check_compatibility(): + # Create a client + client = data_v1beta.BetaAnalyticsDataClient() + + # Initialize request argument(s) + request = data_v1beta.CheckCompatibilityRequest( + ) + + # Make the request + response = client.check_compatibility(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.data_v1beta.types.CheckCompatibilityRequest, dict]): + The request object. The request for compatibility + information for a report's dimensions and metrics. Check + compatibility provides a preview of the compatibility of + a report; fields shared with the `runReport` request + should be the same values as in your `runReport` + request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.data_v1beta.types.CheckCompatibilityResponse: + The compatibility response with the + compatibility of each dimension & + metric. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a analytics_data_api.CheckCompatibilityRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, analytics_data_api.CheckCompatibilityRequest): + request = analytics_data_api.CheckCompatibilityRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.check_compatibility] + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-analytics-data", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "BetaAnalyticsDataClient", +) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/__init__.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/__init__.py new file mode 100644 index 0000000..6a1730d --- /dev/null +++ b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 BetaAnalyticsDataTransport +from .grpc import BetaAnalyticsDataGrpcTransport +from .grpc_asyncio import BetaAnalyticsDataGrpcAsyncIOTransport +from .rest import BetaAnalyticsDataRestTransport +from .rest import BetaAnalyticsDataRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[BetaAnalyticsDataTransport]] +_transport_registry['grpc'] = BetaAnalyticsDataGrpcTransport +_transport_registry['grpc_asyncio'] = BetaAnalyticsDataGrpcAsyncIOTransport +_transport_registry['rest'] = BetaAnalyticsDataRestTransport + +__all__ = ( + 'BetaAnalyticsDataTransport', + 'BetaAnalyticsDataGrpcTransport', + 'BetaAnalyticsDataGrpcAsyncIOTransport', + 'BetaAnalyticsDataRestTransport', + 'BetaAnalyticsDataRestInterceptor', +) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/base.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/base.py new file mode 100644 index 0000000..d158e88 --- /dev/null +++ b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/base.py @@ -0,0 +1,239 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.analytics.data_v1beta.types import analytics_data_api + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-analytics-data', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class BetaAnalyticsDataTransport(abc.ABC): + """Abstract transport class for BetaAnalyticsData.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/analytics', + 'https://www.googleapis.com/auth/analytics.readonly', + ) + + DEFAULT_HOST: str = 'analyticsdata.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. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.run_report: gapic_v1.method.wrap_method( + self.run_report, + default_timeout=60.0, + client_info=client_info, + ), + self.run_pivot_report: gapic_v1.method.wrap_method( + self.run_pivot_report, + default_timeout=60.0, + client_info=client_info, + ), + self.batch_run_reports: gapic_v1.method.wrap_method( + self.batch_run_reports, + default_timeout=60.0, + client_info=client_info, + ), + self.batch_run_pivot_reports: gapic_v1.method.wrap_method( + self.batch_run_pivot_reports, + default_timeout=60.0, + client_info=client_info, + ), + self.get_metadata: gapic_v1.method.wrap_method( + self.get_metadata, + default_timeout=60.0, + client_info=client_info, + ), + self.run_realtime_report: gapic_v1.method.wrap_method( + self.run_realtime_report, + default_timeout=60.0, + client_info=client_info, + ), + self.check_compatibility: gapic_v1.method.wrap_method( + self.check_compatibility, + default_timeout=60.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def run_report(self) -> Callable[ + [analytics_data_api.RunReportRequest], + Union[ + analytics_data_api.RunReportResponse, + Awaitable[analytics_data_api.RunReportResponse] + ]]: + raise NotImplementedError() + + @property + def run_pivot_report(self) -> Callable[ + [analytics_data_api.RunPivotReportRequest], + Union[ + analytics_data_api.RunPivotReportResponse, + Awaitable[analytics_data_api.RunPivotReportResponse] + ]]: + raise NotImplementedError() + + @property + def batch_run_reports(self) -> Callable[ + [analytics_data_api.BatchRunReportsRequest], + Union[ + analytics_data_api.BatchRunReportsResponse, + Awaitable[analytics_data_api.BatchRunReportsResponse] + ]]: + raise NotImplementedError() + + @property + def batch_run_pivot_reports(self) -> Callable[ + [analytics_data_api.BatchRunPivotReportsRequest], + Union[ + analytics_data_api.BatchRunPivotReportsResponse, + Awaitable[analytics_data_api.BatchRunPivotReportsResponse] + ]]: + raise NotImplementedError() + + @property + def get_metadata(self) -> Callable[ + [analytics_data_api.GetMetadataRequest], + Union[ + analytics_data_api.Metadata, + Awaitable[analytics_data_api.Metadata] + ]]: + raise NotImplementedError() + + @property + def run_realtime_report(self) -> Callable[ + [analytics_data_api.RunRealtimeReportRequest], + Union[ + analytics_data_api.RunRealtimeReportResponse, + Awaitable[analytics_data_api.RunRealtimeReportResponse] + ]]: + raise NotImplementedError() + + @property + def check_compatibility(self) -> Callable[ + [analytics_data_api.CheckCompatibilityRequest], + Union[ + analytics_data_api.CheckCompatibilityResponse, + Awaitable[analytics_data_api.CheckCompatibilityResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'BetaAnalyticsDataTransport', +) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc.py new file mode 100644 index 0000000..64eb0db --- /dev/null +++ b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc.py @@ -0,0 +1,467 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.data_v1beta.types import analytics_data_api +from .base import BetaAnalyticsDataTransport, DEFAULT_CLIENT_INFO + + +class BetaAnalyticsDataGrpcTransport(BetaAnalyticsDataTransport): + """gRPC backend transport for BetaAnalyticsData. + + Google Analytics reporting data service. + + 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 = 'analyticsdata.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'analyticsdata.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 run_report(self) -> Callable[ + [analytics_data_api.RunReportRequest], + analytics_data_api.RunReportResponse]: + r"""Return a callable for the run report method over gRPC. + + Returns a customized report of your Google Analytics event data. + Reports contain statistics derived from data collected by the + Google Analytics tracking code. The data returned from the API + is as a table with columns for the requested dimensions and + metrics. Metrics are individual measurements of user activity on + your property, such as active users or event count. Dimensions + break down metrics across some common criteria, such as country + or event name. + + For a guide to constructing requests & understanding responses, + see `Creating a + Report `__. + + Returns: + Callable[[~.RunReportRequest], + ~.RunReportResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_report' not in self._stubs: + self._stubs['run_report'] = self.grpc_channel.unary_unary( + '/google.analytics.data.v1beta.BetaAnalyticsData/RunReport', + request_serializer=analytics_data_api.RunReportRequest.serialize, + response_deserializer=analytics_data_api.RunReportResponse.deserialize, + ) + return self._stubs['run_report'] + + @property + def run_pivot_report(self) -> Callable[ + [analytics_data_api.RunPivotReportRequest], + analytics_data_api.RunPivotReportResponse]: + r"""Return a callable for the run pivot report method over gRPC. + + Returns a customized pivot report of your Google + Analytics event data. Pivot reports are more advanced + and expressive formats than regular reports. In a pivot + report, dimensions are only visible if they are included + in a pivot. Multiple pivots can be specified to further + dissect your data. + + Returns: + Callable[[~.RunPivotReportRequest], + ~.RunPivotReportResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_pivot_report' not in self._stubs: + self._stubs['run_pivot_report'] = self.grpc_channel.unary_unary( + '/google.analytics.data.v1beta.BetaAnalyticsData/RunPivotReport', + request_serializer=analytics_data_api.RunPivotReportRequest.serialize, + response_deserializer=analytics_data_api.RunPivotReportResponse.deserialize, + ) + return self._stubs['run_pivot_report'] + + @property + def batch_run_reports(self) -> Callable[ + [analytics_data_api.BatchRunReportsRequest], + analytics_data_api.BatchRunReportsResponse]: + r"""Return a callable for the batch run reports method over gRPC. + + Returns multiple reports in a batch. All reports must + be for the same GA4 Property. + + Returns: + Callable[[~.BatchRunReportsRequest], + ~.BatchRunReportsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_run_reports' not in self._stubs: + self._stubs['batch_run_reports'] = self.grpc_channel.unary_unary( + '/google.analytics.data.v1beta.BetaAnalyticsData/BatchRunReports', + request_serializer=analytics_data_api.BatchRunReportsRequest.serialize, + response_deserializer=analytics_data_api.BatchRunReportsResponse.deserialize, + ) + return self._stubs['batch_run_reports'] + + @property + def batch_run_pivot_reports(self) -> Callable[ + [analytics_data_api.BatchRunPivotReportsRequest], + analytics_data_api.BatchRunPivotReportsResponse]: + r"""Return a callable for the batch run pivot reports method over gRPC. + + Returns multiple pivot reports in a batch. All + reports must be for the same GA4 Property. + + Returns: + Callable[[~.BatchRunPivotReportsRequest], + ~.BatchRunPivotReportsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_run_pivot_reports' not in self._stubs: + self._stubs['batch_run_pivot_reports'] = self.grpc_channel.unary_unary( + '/google.analytics.data.v1beta.BetaAnalyticsData/BatchRunPivotReports', + request_serializer=analytics_data_api.BatchRunPivotReportsRequest.serialize, + response_deserializer=analytics_data_api.BatchRunPivotReportsResponse.deserialize, + ) + return self._stubs['batch_run_pivot_reports'] + + @property + def get_metadata(self) -> Callable[ + [analytics_data_api.GetMetadataRequest], + analytics_data_api.Metadata]: + r"""Return a callable for the get metadata method over gRPC. + + Returns metadata for dimensions and metrics available in + reporting methods. Used to explore the dimensions and metrics. + In this method, a Google Analytics GA4 Property Identifier is + specified in the request, and the metadata response includes + Custom dimensions and metrics as well as Universal metadata. + + For example if a custom metric with parameter name + ``levels_unlocked`` is registered to a property, the Metadata + response will contain ``customEvent:levels_unlocked``. Universal + metadata are dimensions and metrics applicable to any property + such as ``country`` and ``totalUsers``. + + Returns: + Callable[[~.GetMetadataRequest], + ~.Metadata]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_metadata' not in self._stubs: + self._stubs['get_metadata'] = self.grpc_channel.unary_unary( + '/google.analytics.data.v1beta.BetaAnalyticsData/GetMetadata', + request_serializer=analytics_data_api.GetMetadataRequest.serialize, + response_deserializer=analytics_data_api.Metadata.deserialize, + ) + return self._stubs['get_metadata'] + + @property + def run_realtime_report(self) -> Callable[ + [analytics_data_api.RunRealtimeReportRequest], + analytics_data_api.RunRealtimeReportResponse]: + r"""Return a callable for the run realtime report method over gRPC. + + Returns a customized report of realtime event data for your + property. Events appear in realtime reports seconds after they + have been sent to the Google Analytics. Realtime reports show + events and usage data for the periods of time ranging from the + present moment to 30 minutes ago (up to 60 minutes for Google + Analytics 360 properties). + + For a guide to constructing realtime requests & understanding + responses, see `Creating a Realtime + Report `__. + + Returns: + Callable[[~.RunRealtimeReportRequest], + ~.RunRealtimeReportResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_realtime_report' not in self._stubs: + self._stubs['run_realtime_report'] = self.grpc_channel.unary_unary( + '/google.analytics.data.v1beta.BetaAnalyticsData/RunRealtimeReport', + request_serializer=analytics_data_api.RunRealtimeReportRequest.serialize, + response_deserializer=analytics_data_api.RunRealtimeReportResponse.deserialize, + ) + return self._stubs['run_realtime_report'] + + @property + def check_compatibility(self) -> Callable[ + [analytics_data_api.CheckCompatibilityRequest], + analytics_data_api.CheckCompatibilityResponse]: + r"""Return a callable for the check compatibility method over gRPC. + + This compatibility method lists dimensions and + metrics that can be added to a report request and + maintain compatibility. This method fails if the + request's dimensions and metrics are incompatible. + In Google Analytics, reports fail if they request + incompatible dimensions and/or metrics; in that case, + you will need to remove dimensions and/or metrics from + the incompatible report until the report is compatible. + The Realtime and Core reports have different + compatibility rules. This method checks compatibility + for Core reports. + + Returns: + Callable[[~.CheckCompatibilityRequest], + ~.CheckCompatibilityResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'check_compatibility' not in self._stubs: + self._stubs['check_compatibility'] = self.grpc_channel.unary_unary( + '/google.analytics.data.v1beta.BetaAnalyticsData/CheckCompatibility', + request_serializer=analytics_data_api.CheckCompatibilityRequest.serialize, + response_deserializer=analytics_data_api.CheckCompatibilityResponse.deserialize, + ) + return self._stubs['check_compatibility'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'BetaAnalyticsDataGrpcTransport', +) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc_asyncio.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc_asyncio.py new file mode 100644 index 0000000..8e27253 --- /dev/null +++ b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc_asyncio.py @@ -0,0 +1,466 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.analytics.data_v1beta.types import analytics_data_api +from .base import BetaAnalyticsDataTransport, DEFAULT_CLIENT_INFO +from .grpc import BetaAnalyticsDataGrpcTransport + + +class BetaAnalyticsDataGrpcAsyncIOTransport(BetaAnalyticsDataTransport): + """gRPC AsyncIO backend transport for BetaAnalyticsData. + + Google Analytics reporting data service. + + 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 = 'analyticsdata.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'analyticsdata.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def run_report(self) -> Callable[ + [analytics_data_api.RunReportRequest], + Awaitable[analytics_data_api.RunReportResponse]]: + r"""Return a callable for the run report method over gRPC. + + Returns a customized report of your Google Analytics event data. + Reports contain statistics derived from data collected by the + Google Analytics tracking code. The data returned from the API + is as a table with columns for the requested dimensions and + metrics. Metrics are individual measurements of user activity on + your property, such as active users or event count. Dimensions + break down metrics across some common criteria, such as country + or event name. + + For a guide to constructing requests & understanding responses, + see `Creating a + Report `__. + + Returns: + Callable[[~.RunReportRequest], + Awaitable[~.RunReportResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_report' not in self._stubs: + self._stubs['run_report'] = self.grpc_channel.unary_unary( + '/google.analytics.data.v1beta.BetaAnalyticsData/RunReport', + request_serializer=analytics_data_api.RunReportRequest.serialize, + response_deserializer=analytics_data_api.RunReportResponse.deserialize, + ) + return self._stubs['run_report'] + + @property + def run_pivot_report(self) -> Callable[ + [analytics_data_api.RunPivotReportRequest], + Awaitable[analytics_data_api.RunPivotReportResponse]]: + r"""Return a callable for the run pivot report method over gRPC. + + Returns a customized pivot report of your Google + Analytics event data. Pivot reports are more advanced + and expressive formats than regular reports. In a pivot + report, dimensions are only visible if they are included + in a pivot. Multiple pivots can be specified to further + dissect your data. + + Returns: + Callable[[~.RunPivotReportRequest], + Awaitable[~.RunPivotReportResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_pivot_report' not in self._stubs: + self._stubs['run_pivot_report'] = self.grpc_channel.unary_unary( + '/google.analytics.data.v1beta.BetaAnalyticsData/RunPivotReport', + request_serializer=analytics_data_api.RunPivotReportRequest.serialize, + response_deserializer=analytics_data_api.RunPivotReportResponse.deserialize, + ) + return self._stubs['run_pivot_report'] + + @property + def batch_run_reports(self) -> Callable[ + [analytics_data_api.BatchRunReportsRequest], + Awaitable[analytics_data_api.BatchRunReportsResponse]]: + r"""Return a callable for the batch run reports method over gRPC. + + Returns multiple reports in a batch. All reports must + be for the same GA4 Property. + + Returns: + Callable[[~.BatchRunReportsRequest], + Awaitable[~.BatchRunReportsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_run_reports' not in self._stubs: + self._stubs['batch_run_reports'] = self.grpc_channel.unary_unary( + '/google.analytics.data.v1beta.BetaAnalyticsData/BatchRunReports', + request_serializer=analytics_data_api.BatchRunReportsRequest.serialize, + response_deserializer=analytics_data_api.BatchRunReportsResponse.deserialize, + ) + return self._stubs['batch_run_reports'] + + @property + def batch_run_pivot_reports(self) -> Callable[ + [analytics_data_api.BatchRunPivotReportsRequest], + Awaitable[analytics_data_api.BatchRunPivotReportsResponse]]: + r"""Return a callable for the batch run pivot reports method over gRPC. + + Returns multiple pivot reports in a batch. All + reports must be for the same GA4 Property. + + Returns: + Callable[[~.BatchRunPivotReportsRequest], + Awaitable[~.BatchRunPivotReportsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_run_pivot_reports' not in self._stubs: + self._stubs['batch_run_pivot_reports'] = self.grpc_channel.unary_unary( + '/google.analytics.data.v1beta.BetaAnalyticsData/BatchRunPivotReports', + request_serializer=analytics_data_api.BatchRunPivotReportsRequest.serialize, + response_deserializer=analytics_data_api.BatchRunPivotReportsResponse.deserialize, + ) + return self._stubs['batch_run_pivot_reports'] + + @property + def get_metadata(self) -> Callable[ + [analytics_data_api.GetMetadataRequest], + Awaitable[analytics_data_api.Metadata]]: + r"""Return a callable for the get metadata method over gRPC. + + Returns metadata for dimensions and metrics available in + reporting methods. Used to explore the dimensions and metrics. + In this method, a Google Analytics GA4 Property Identifier is + specified in the request, and the metadata response includes + Custom dimensions and metrics as well as Universal metadata. + + For example if a custom metric with parameter name + ``levels_unlocked`` is registered to a property, the Metadata + response will contain ``customEvent:levels_unlocked``. Universal + metadata are dimensions and metrics applicable to any property + such as ``country`` and ``totalUsers``. + + Returns: + Callable[[~.GetMetadataRequest], + Awaitable[~.Metadata]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_metadata' not in self._stubs: + self._stubs['get_metadata'] = self.grpc_channel.unary_unary( + '/google.analytics.data.v1beta.BetaAnalyticsData/GetMetadata', + request_serializer=analytics_data_api.GetMetadataRequest.serialize, + response_deserializer=analytics_data_api.Metadata.deserialize, + ) + return self._stubs['get_metadata'] + + @property + def run_realtime_report(self) -> Callable[ + [analytics_data_api.RunRealtimeReportRequest], + Awaitable[analytics_data_api.RunRealtimeReportResponse]]: + r"""Return a callable for the run realtime report method over gRPC. + + Returns a customized report of realtime event data for your + property. Events appear in realtime reports seconds after they + have been sent to the Google Analytics. Realtime reports show + events and usage data for the periods of time ranging from the + present moment to 30 minutes ago (up to 60 minutes for Google + Analytics 360 properties). + + For a guide to constructing realtime requests & understanding + responses, see `Creating a Realtime + Report `__. + + Returns: + Callable[[~.RunRealtimeReportRequest], + Awaitable[~.RunRealtimeReportResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_realtime_report' not in self._stubs: + self._stubs['run_realtime_report'] = self.grpc_channel.unary_unary( + '/google.analytics.data.v1beta.BetaAnalyticsData/RunRealtimeReport', + request_serializer=analytics_data_api.RunRealtimeReportRequest.serialize, + response_deserializer=analytics_data_api.RunRealtimeReportResponse.deserialize, + ) + return self._stubs['run_realtime_report'] + + @property + def check_compatibility(self) -> Callable[ + [analytics_data_api.CheckCompatibilityRequest], + Awaitable[analytics_data_api.CheckCompatibilityResponse]]: + r"""Return a callable for the check compatibility method over gRPC. + + This compatibility method lists dimensions and + metrics that can be added to a report request and + maintain compatibility. This method fails if the + request's dimensions and metrics are incompatible. + In Google Analytics, reports fail if they request + incompatible dimensions and/or metrics; in that case, + you will need to remove dimensions and/or metrics from + the incompatible report until the report is compatible. + The Realtime and Core reports have different + compatibility rules. This method checks compatibility + for Core reports. + + Returns: + Callable[[~.CheckCompatibilityRequest], + Awaitable[~.CheckCompatibilityResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'check_compatibility' not in self._stubs: + self._stubs['check_compatibility'] = self.grpc_channel.unary_unary( + '/google.analytics.data.v1beta.BetaAnalyticsData/CheckCompatibility', + request_serializer=analytics_data_api.CheckCompatibilityRequest.serialize, + response_deserializer=analytics_data_api.CheckCompatibilityResponse.deserialize, + ) + return self._stubs['check_compatibility'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'BetaAnalyticsDataGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/rest.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/rest.py new file mode 100644 index 0000000..0be2b18 --- /dev/null +++ b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/rest.py @@ -0,0 +1,970 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.analytics.data_v1beta.types import analytics_data_api + +from .base import BetaAnalyticsDataTransport, 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 BetaAnalyticsDataRestInterceptor: + """Interceptor for BetaAnalyticsData. + + 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 BetaAnalyticsDataRestTransport. + + .. code-block:: python + class MyCustomBetaAnalyticsDataInterceptor(BetaAnalyticsDataRestInterceptor): + def pre_batch_run_pivot_reports(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_run_pivot_reports(response): + logging.log(f"Received response: {response}") + + def pre_batch_run_reports(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_run_reports(response): + logging.log(f"Received response: {response}") + + def pre_check_compatibility(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_check_compatibility(response): + logging.log(f"Received response: {response}") + + def pre_get_metadata(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_metadata(response): + logging.log(f"Received response: {response}") + + def pre_run_pivot_report(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_run_pivot_report(response): + logging.log(f"Received response: {response}") + + def pre_run_realtime_report(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_run_realtime_report(response): + logging.log(f"Received response: {response}") + + def pre_run_report(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_run_report(response): + logging.log(f"Received response: {response}") + + transport = BetaAnalyticsDataRestTransport(interceptor=MyCustomBetaAnalyticsDataInterceptor()) + client = BetaAnalyticsDataClient(transport=transport) + + + """ + def pre_batch_run_pivot_reports(self, request: analytics_data_api.BatchRunPivotReportsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_data_api.BatchRunPivotReportsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_run_pivot_reports + + Override in a subclass to manipulate the request or metadata + before they are sent to the BetaAnalyticsData server. + """ + return request, metadata + + def post_batch_run_pivot_reports(self, response: analytics_data_api.BatchRunPivotReportsResponse) -> analytics_data_api.BatchRunPivotReportsResponse: + """Post-rpc interceptor for batch_run_pivot_reports + + Override in a subclass to manipulate the response + after it is returned by the BetaAnalyticsData server but before + it is returned to user code. + """ + return response + def pre_batch_run_reports(self, request: analytics_data_api.BatchRunReportsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_data_api.BatchRunReportsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_run_reports + + Override in a subclass to manipulate the request or metadata + before they are sent to the BetaAnalyticsData server. + """ + return request, metadata + + def post_batch_run_reports(self, response: analytics_data_api.BatchRunReportsResponse) -> analytics_data_api.BatchRunReportsResponse: + """Post-rpc interceptor for batch_run_reports + + Override in a subclass to manipulate the response + after it is returned by the BetaAnalyticsData server but before + it is returned to user code. + """ + return response + def pre_check_compatibility(self, request: analytics_data_api.CheckCompatibilityRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_data_api.CheckCompatibilityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for check_compatibility + + Override in a subclass to manipulate the request or metadata + before they are sent to the BetaAnalyticsData server. + """ + return request, metadata + + def post_check_compatibility(self, response: analytics_data_api.CheckCompatibilityResponse) -> analytics_data_api.CheckCompatibilityResponse: + """Post-rpc interceptor for check_compatibility + + Override in a subclass to manipulate the response + after it is returned by the BetaAnalyticsData server but before + it is returned to user code. + """ + return response + def pre_get_metadata(self, request: analytics_data_api.GetMetadataRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_data_api.GetMetadataRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_metadata + + Override in a subclass to manipulate the request or metadata + before they are sent to the BetaAnalyticsData server. + """ + return request, metadata + + def post_get_metadata(self, response: analytics_data_api.Metadata) -> analytics_data_api.Metadata: + """Post-rpc interceptor for get_metadata + + Override in a subclass to manipulate the response + after it is returned by the BetaAnalyticsData server but before + it is returned to user code. + """ + return response + def pre_run_pivot_report(self, request: analytics_data_api.RunPivotReportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_data_api.RunPivotReportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for run_pivot_report + + Override in a subclass to manipulate the request or metadata + before they are sent to the BetaAnalyticsData server. + """ + return request, metadata + + def post_run_pivot_report(self, response: analytics_data_api.RunPivotReportResponse) -> analytics_data_api.RunPivotReportResponse: + """Post-rpc interceptor for run_pivot_report + + Override in a subclass to manipulate the response + after it is returned by the BetaAnalyticsData server but before + it is returned to user code. + """ + return response + def pre_run_realtime_report(self, request: analytics_data_api.RunRealtimeReportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_data_api.RunRealtimeReportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for run_realtime_report + + Override in a subclass to manipulate the request or metadata + before they are sent to the BetaAnalyticsData server. + """ + return request, metadata + + def post_run_realtime_report(self, response: analytics_data_api.RunRealtimeReportResponse) -> analytics_data_api.RunRealtimeReportResponse: + """Post-rpc interceptor for run_realtime_report + + Override in a subclass to manipulate the response + after it is returned by the BetaAnalyticsData server but before + it is returned to user code. + """ + return response + def pre_run_report(self, request: analytics_data_api.RunReportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_data_api.RunReportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for run_report + + Override in a subclass to manipulate the request or metadata + before they are sent to the BetaAnalyticsData server. + """ + return request, metadata + + def post_run_report(self, response: analytics_data_api.RunReportResponse) -> analytics_data_api.RunReportResponse: + """Post-rpc interceptor for run_report + + Override in a subclass to manipulate the response + after it is returned by the BetaAnalyticsData server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class BetaAnalyticsDataRestStub: + _session: AuthorizedSession + _host: str + _interceptor: BetaAnalyticsDataRestInterceptor + + +class BetaAnalyticsDataRestTransport(BetaAnalyticsDataTransport): + """REST backend transport for BetaAnalyticsData. + + Google Analytics reporting data service. + + 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 + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via an issue in this + library's source repository. Thank you! + """ + + def __init__(self, *, + host: str = 'analyticsdata.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[BetaAnalyticsDataRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is 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 BetaAnalyticsDataRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _BatchRunPivotReports(BetaAnalyticsDataRestStub): + def __hash__(self): + return hash("BatchRunPivotReports") + + def __call__(self, + request: analytics_data_api.BatchRunPivotReportsRequest, *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.BatchRunPivotReportsResponse: + r"""Call the batch run pivot reports method over HTTP. + + Args: + request (~.analytics_data_api.BatchRunPivotReportsRequest): + The request object. The batch request containing multiple + pivot report requests. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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_data_api.BatchRunPivotReportsResponse: + The batch response containing + multiple pivot reports. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{property=properties/*}:batchRunPivotReports', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_batch_run_pivot_reports(request, metadata) + pb_request = analytics_data_api.BatchRunPivotReportsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=False + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=False, + )) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._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_data_api.BatchRunPivotReportsResponse() + pb_resp = analytics_data_api.BatchRunPivotReportsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_run_pivot_reports(resp) + return resp + + class _BatchRunReports(BetaAnalyticsDataRestStub): + def __hash__(self): + return hash("BatchRunReports") + + def __call__(self, + request: analytics_data_api.BatchRunReportsRequest, *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.BatchRunReportsResponse: + r"""Call the batch run reports method over HTTP. + + Args: + request (~.analytics_data_api.BatchRunReportsRequest): + The request object. The batch request containing multiple + report requests. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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_data_api.BatchRunReportsResponse: + The batch response containing + multiple reports. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{property=properties/*}:batchRunReports', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_batch_run_reports(request, metadata) + pb_request = analytics_data_api.BatchRunReportsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=False + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=False, + )) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._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_data_api.BatchRunReportsResponse() + pb_resp = analytics_data_api.BatchRunReportsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_run_reports(resp) + return resp + + class _CheckCompatibility(BetaAnalyticsDataRestStub): + def __hash__(self): + return hash("CheckCompatibility") + + def __call__(self, + request: analytics_data_api.CheckCompatibilityRequest, *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.CheckCompatibilityResponse: + r"""Call the check compatibility method over HTTP. + + Args: + request (~.analytics_data_api.CheckCompatibilityRequest): + The request object. The request for compatibility information for a report's + dimensions and metrics. Check compatibility provides a + preview of the compatibility of a report; fields shared + with the ``runReport`` request should be the same values + as in your ``runReport`` request. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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_data_api.CheckCompatibilityResponse: + The compatibility response with the + compatibility of each dimension & + metric. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{property=properties/*}:checkCompatibility', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_check_compatibility(request, metadata) + pb_request = analytics_data_api.CheckCompatibilityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=False + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=False, + )) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._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_data_api.CheckCompatibilityResponse() + pb_resp = analytics_data_api.CheckCompatibilityResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_check_compatibility(resp) + return resp + + class _GetMetadata(BetaAnalyticsDataRestStub): + def __hash__(self): + return hash("GetMetadata") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_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_data_api.GetMetadataRequest, *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.Metadata: + r"""Call the get metadata method over HTTP. + + Args: + request (~.analytics_data_api.GetMetadataRequest): + The request object. Request for a property's dimension + and metric metadata. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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_data_api.Metadata: + The dimensions and metrics currently + accepted in reporting methods. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=properties/*/metadata}', + }, + ] + request, metadata = self._interceptor.pre_get_metadata(request, metadata) + pb_request = analytics_data_api.GetMetadataRequest.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'], + including_default_value_fields=False, + use_integers_for_enums=False, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, 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_data_api.Metadata() + pb_resp = analytics_data_api.Metadata.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_metadata(resp) + return resp + + class _RunPivotReport(BetaAnalyticsDataRestStub): + def __hash__(self): + return hash("RunPivotReport") + + def __call__(self, + request: analytics_data_api.RunPivotReportRequest, *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.RunPivotReportResponse: + r"""Call the run pivot report method over HTTP. + + Args: + request (~.analytics_data_api.RunPivotReportRequest): + The request object. The request to generate a pivot + 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_data_api.RunPivotReportResponse: + The response pivot report table + corresponding to a pivot request. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{property=properties/*}:runPivotReport', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_run_pivot_report(request, metadata) + pb_request = analytics_data_api.RunPivotReportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=False + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=False, + )) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._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_data_api.RunPivotReportResponse() + pb_resp = analytics_data_api.RunPivotReportResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_run_pivot_report(resp) + return resp + + class _RunRealtimeReport(BetaAnalyticsDataRestStub): + def __hash__(self): + return hash("RunRealtimeReport") + + def __call__(self, + request: analytics_data_api.RunRealtimeReportRequest, *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.RunRealtimeReportResponse: + r"""Call the run realtime report method over HTTP. + + Args: + request (~.analytics_data_api.RunRealtimeReportRequest): + The request object. The request to generate a realtime + 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_data_api.RunRealtimeReportResponse: + The response realtime report table + corresponding to a request. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{property=properties/*}:runRealtimeReport', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_run_realtime_report(request, metadata) + pb_request = analytics_data_api.RunRealtimeReportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=False + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=False, + )) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._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_data_api.RunRealtimeReportResponse() + pb_resp = analytics_data_api.RunRealtimeReportResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_run_realtime_report(resp) + return resp + + class _RunReport(BetaAnalyticsDataRestStub): + def __hash__(self): + return hash("RunReport") + + def __call__(self, + request: analytics_data_api.RunReportRequest, *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_data_api.RunReportResponse: + r"""Call the run report method over HTTP. + + Args: + request (~.analytics_data_api.RunReportRequest): + The request object. The request to generate a 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_data_api.RunReportResponse: + The response report table + corresponding to a request. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{property=properties/*}:runReport', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_run_report(request, metadata) + pb_request = analytics_data_api.RunReportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=False + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=False, + )) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._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_data_api.RunReportResponse() + pb_resp = analytics_data_api.RunReportResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_run_report(resp) + return resp + + @property + def batch_run_pivot_reports(self) -> Callable[ + [analytics_data_api.BatchRunPivotReportsRequest], + analytics_data_api.BatchRunPivotReportsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchRunPivotReports(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_run_reports(self) -> Callable[ + [analytics_data_api.BatchRunReportsRequest], + analytics_data_api.BatchRunReportsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchRunReports(self._session, self._host, self._interceptor) # type: ignore + + @property + def check_compatibility(self) -> Callable[ + [analytics_data_api.CheckCompatibilityRequest], + analytics_data_api.CheckCompatibilityResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CheckCompatibility(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_metadata(self) -> Callable[ + [analytics_data_api.GetMetadataRequest], + analytics_data_api.Metadata]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetMetadata(self._session, self._host, self._interceptor) # type: ignore + + @property + def run_pivot_report(self) -> Callable[ + [analytics_data_api.RunPivotReportRequest], + analytics_data_api.RunPivotReportResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RunPivotReport(self._session, self._host, self._interceptor) # type: ignore + + @property + def run_realtime_report(self) -> Callable[ + [analytics_data_api.RunRealtimeReportRequest], + analytics_data_api.RunRealtimeReportResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RunRealtimeReport(self._session, self._host, self._interceptor) # type: ignore + + @property + def run_report(self) -> Callable[ + [analytics_data_api.RunReportRequest], + analytics_data_api.RunReportResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RunReport(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'BetaAnalyticsDataRestTransport', +) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/types/__init__.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/types/__init__.py new file mode 100644 index 0000000..36ff6ec --- /dev/null +++ b/owl-bot-staging/v1beta/google/analytics/data_v1beta/types/__init__.py @@ -0,0 +1,116 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .analytics_data_api import ( + BatchRunPivotReportsRequest, + BatchRunPivotReportsResponse, + BatchRunReportsRequest, + BatchRunReportsResponse, + CheckCompatibilityRequest, + CheckCompatibilityResponse, + GetMetadataRequest, + Metadata, + RunPivotReportRequest, + RunPivotReportResponse, + RunRealtimeReportRequest, + RunRealtimeReportResponse, + RunReportRequest, + RunReportResponse, +) +from .data import ( + Cohort, + CohortReportSettings, + CohortSpec, + CohortsRange, + DateRange, + Dimension, + DimensionCompatibility, + DimensionExpression, + DimensionHeader, + DimensionMetadata, + DimensionValue, + Filter, + FilterExpression, + FilterExpressionList, + Metric, + MetricCompatibility, + MetricHeader, + MetricMetadata, + MetricValue, + MinuteRange, + NumericValue, + OrderBy, + Pivot, + PivotDimensionHeader, + PivotHeader, + PropertyQuota, + QuotaStatus, + ResponseMetaData, + Row, + Compatibility, + MetricAggregation, + MetricType, + RestrictedMetricType, +) + +__all__ = ( + 'BatchRunPivotReportsRequest', + 'BatchRunPivotReportsResponse', + 'BatchRunReportsRequest', + 'BatchRunReportsResponse', + 'CheckCompatibilityRequest', + 'CheckCompatibilityResponse', + 'GetMetadataRequest', + 'Metadata', + 'RunPivotReportRequest', + 'RunPivotReportResponse', + 'RunRealtimeReportRequest', + 'RunRealtimeReportResponse', + 'RunReportRequest', + 'RunReportResponse', + 'Cohort', + 'CohortReportSettings', + 'CohortSpec', + 'CohortsRange', + 'DateRange', + 'Dimension', + 'DimensionCompatibility', + 'DimensionExpression', + 'DimensionHeader', + 'DimensionMetadata', + 'DimensionValue', + 'Filter', + 'FilterExpression', + 'FilterExpressionList', + 'Metric', + 'MetricCompatibility', + 'MetricHeader', + 'MetricMetadata', + 'MetricValue', + 'MinuteRange', + 'NumericValue', + 'OrderBy', + 'Pivot', + 'PivotDimensionHeader', + 'PivotHeader', + 'PropertyQuota', + 'QuotaStatus', + 'ResponseMetaData', + 'Row', + 'Compatibility', + 'MetricAggregation', + 'MetricType', + 'RestrictedMetricType', +) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/types/analytics_data_api.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/types/analytics_data_api.py new file mode 100644 index 0000000..41abbfc --- /dev/null +++ b/owl-bot-staging/v1beta/google/analytics/data_v1beta/types/analytics_data_api.py @@ -0,0 +1,978 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.analytics.data_v1beta.types import data + + +__protobuf__ = proto.module( + package='google.analytics.data.v1beta', + manifest={ + 'CheckCompatibilityRequest', + 'CheckCompatibilityResponse', + 'Metadata', + 'RunReportRequest', + 'RunReportResponse', + 'RunPivotReportRequest', + 'RunPivotReportResponse', + 'BatchRunReportsRequest', + 'BatchRunReportsResponse', + 'BatchRunPivotReportsRequest', + 'BatchRunPivotReportsResponse', + 'GetMetadataRequest', + 'RunRealtimeReportRequest', + 'RunRealtimeReportResponse', + }, +) + + +class CheckCompatibilityRequest(proto.Message): + r"""The request for compatibility information for a report's dimensions + and metrics. Check compatibility provides a preview of the + compatibility of a report; fields shared with the ``runReport`` + request should be the same values as in your ``runReport`` request. + + Attributes: + property (str): + A Google Analytics GA4 property identifier whose events are + tracked. To learn more, see `where to find your Property + ID `__. + ``property`` should be the same value as in your + ``runReport`` request. + + Example: properties/1234 + + Set the Property ID to 0 for compatibility checking on + dimensions and metrics common to all properties. In this + special mode, this method will not return custom dimensions + and metrics. + dimensions (MutableSequence[google.analytics.data_v1beta.types.Dimension]): + The dimensions in this report. ``dimensions`` should be the + same value as in your ``runReport`` request. + metrics (MutableSequence[google.analytics.data_v1beta.types.Metric]): + The metrics in this report. ``metrics`` should be the same + value as in your ``runReport`` request. + dimension_filter (google.analytics.data_v1beta.types.FilterExpression): + The filter clause of dimensions. ``dimensionFilter`` should + be the same value as in your ``runReport`` request. + metric_filter (google.analytics.data_v1beta.types.FilterExpression): + The filter clause of metrics. ``metricFilter`` should be the + same value as in your ``runReport`` request + compatibility_filter (google.analytics.data_v1beta.types.Compatibility): + Filters the dimensions and metrics in the response to just + this compatibility. Commonly used as + ``”compatibilityFilter”: “COMPATIBLE”`` to only return + compatible dimensions & metrics. + """ + + property: str = proto.Field( + proto.STRING, + number=1, + ) + dimensions: MutableSequence[data.Dimension] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=data.Dimension, + ) + metrics: MutableSequence[data.Metric] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=data.Metric, + ) + dimension_filter: data.FilterExpression = proto.Field( + proto.MESSAGE, + number=4, + message=data.FilterExpression, + ) + metric_filter: data.FilterExpression = proto.Field( + proto.MESSAGE, + number=5, + message=data.FilterExpression, + ) + compatibility_filter: data.Compatibility = proto.Field( + proto.ENUM, + number=6, + enum=data.Compatibility, + ) + + +class CheckCompatibilityResponse(proto.Message): + r"""The compatibility response with the compatibility of each + dimension & metric. + + Attributes: + dimension_compatibilities (MutableSequence[google.analytics.data_v1beta.types.DimensionCompatibility]): + The compatibility of each dimension. + metric_compatibilities (MutableSequence[google.analytics.data_v1beta.types.MetricCompatibility]): + The compatibility of each metric. + """ + + dimension_compatibilities: MutableSequence[data.DimensionCompatibility] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=data.DimensionCompatibility, + ) + metric_compatibilities: MutableSequence[data.MetricCompatibility] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=data.MetricCompatibility, + ) + + +class Metadata(proto.Message): + r"""The dimensions and metrics currently accepted in reporting + methods. + + Attributes: + name (str): + Resource name of this metadata. + dimensions (MutableSequence[google.analytics.data_v1beta.types.DimensionMetadata]): + The dimension descriptions. + metrics (MutableSequence[google.analytics.data_v1beta.types.MetricMetadata]): + The metric descriptions. + """ + + name: str = proto.Field( + proto.STRING, + number=3, + ) + dimensions: MutableSequence[data.DimensionMetadata] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=data.DimensionMetadata, + ) + metrics: MutableSequence[data.MetricMetadata] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=data.MetricMetadata, + ) + + +class RunReportRequest(proto.Message): + r"""The request to generate a report. + + Attributes: + property (str): + A Google Analytics GA4 property identifier whose events are + tracked. Specified in the URL path and not the body. To + learn more, see `where to find your Property + ID `__. + Within a batch request, this property should either be + unspecified or consistent with the batch-level property. + + Example: properties/1234 + dimensions (MutableSequence[google.analytics.data_v1beta.types.Dimension]): + The dimensions requested and displayed. + metrics (MutableSequence[google.analytics.data_v1beta.types.Metric]): + The metrics requested and displayed. + date_ranges (MutableSequence[google.analytics.data_v1beta.types.DateRange]): + Date ranges of data 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 event data for + the overlapping days is included in the response rows for + both date ranges. In a cohort request, this ``dateRanges`` + must be unspecified. + dimension_filter (google.analytics.data_v1beta.types.FilterExpression): + Dimension filters allow you to ask for only specific + dimension values in the report. To learn more, see + `Fundamentals of Dimension + Filters `__ + for examples. Metrics cannot be used in this filter. + metric_filter (google.analytics.data_v1beta.types.FilterExpression): + The filter clause of metrics. 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. + + When paging, the first request does not specify offset; or + equivalently, sets offset to 0; the first request returns + the first ``limit`` of rows. The second request sets offset + to the ``limit`` of the first request; the second request + returns the second ``limit`` of rows. + + 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 can also return fewer rows than the requested + ``limit``, if there aren't as many dimension values 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 `__. + metric_aggregations (MutableSequence[google.analytics.data_v1beta.types.MetricAggregation]): + Aggregation of metrics. Aggregated metric values will be + shown in rows where the dimension_values are set to + "RESERVED_(MetricAggregation)". + order_bys (MutableSequence[google.analytics.data_v1beta.types.OrderBy]): + Specifies how rows are ordered in the + response. + currency_code (str): + A currency code in ISO4217 format, such as + "AED", "USD", "JPY". If the field is empty, the + report uses the property's default currency. + cohort_spec (google.analytics.data_v1beta.types.CohortSpec): + Cohort group associated with this request. If + there is a cohort group in the request the + 'cohort' dimension must be present. + keep_empty_rows (bool): + If false or unspecified, each row with all + metrics equal to 0 will not be returned. If + true, these rows will be returned if they are + not separately removed by a filter. + return_property_quota (bool): + Toggles whether to return the current state of this + Analytics Property's quota. Quota is returned in + `PropertyQuota <#PropertyQuota>`__. + """ + + property: str = proto.Field( + proto.STRING, + number=1, + ) + dimensions: MutableSequence[data.Dimension] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=data.Dimension, + ) + metrics: MutableSequence[data.Metric] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=data.Metric, + ) + date_ranges: MutableSequence[data.DateRange] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=data.DateRange, + ) + dimension_filter: data.FilterExpression = proto.Field( + proto.MESSAGE, + number=5, + message=data.FilterExpression, + ) + metric_filter: data.FilterExpression = proto.Field( + proto.MESSAGE, + number=6, + message=data.FilterExpression, + ) + offset: int = proto.Field( + proto.INT64, + number=7, + ) + limit: int = proto.Field( + proto.INT64, + number=8, + ) + metric_aggregations: MutableSequence[data.MetricAggregation] = proto.RepeatedField( + proto.ENUM, + number=9, + enum=data.MetricAggregation, + ) + order_bys: MutableSequence[data.OrderBy] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=data.OrderBy, + ) + currency_code: str = proto.Field( + proto.STRING, + number=11, + ) + cohort_spec: data.CohortSpec = proto.Field( + proto.MESSAGE, + number=12, + message=data.CohortSpec, + ) + keep_empty_rows: bool = proto.Field( + proto.BOOL, + number=13, + ) + return_property_quota: bool = proto.Field( + proto.BOOL, + number=14, + ) + + +class RunReportResponse(proto.Message): + r"""The response report table corresponding to a request. + + Attributes: + dimension_headers (MutableSequence[google.analytics.data_v1beta.types.DimensionHeader]): + Describes dimension columns. The number of + DimensionHeaders and ordering of + DimensionHeaders matches the dimensions present + in rows. + metric_headers (MutableSequence[google.analytics.data_v1beta.types.MetricHeader]): + Describes metric columns. The number of + MetricHeaders and ordering of MetricHeaders + matches the metrics present in rows. + rows (MutableSequence[google.analytics.data_v1beta.types.Row]): + Rows of dimension value combinations and + metric values in the report. + totals (MutableSequence[google.analytics.data_v1beta.types.Row]): + If requested, the totaled values of metrics. + maximums (MutableSequence[google.analytics.data_v1beta.types.Row]): + If requested, the maximum values of metrics. + minimums (MutableSequence[google.analytics.data_v1beta.types.Row]): + If requested, the minimum values of metrics. + 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 `__. + metadata (google.analytics.data_v1beta.types.ResponseMetaData): + Metadata for the report. + property_quota (google.analytics.data_v1beta.types.PropertyQuota): + This Analytics Property's quota state + including this request. + kind (str): + Identifies what kind of resource this message is. This + ``kind`` is always the fixed string + "analyticsData#runReport". Useful to distinguish between + response types in JSON. + """ + + dimension_headers: MutableSequence[data.DimensionHeader] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=data.DimensionHeader, + ) + metric_headers: MutableSequence[data.MetricHeader] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=data.MetricHeader, + ) + rows: MutableSequence[data.Row] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=data.Row, + ) + totals: MutableSequence[data.Row] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=data.Row, + ) + maximums: MutableSequence[data.Row] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=data.Row, + ) + minimums: MutableSequence[data.Row] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=data.Row, + ) + row_count: int = proto.Field( + proto.INT32, + number=7, + ) + metadata: data.ResponseMetaData = proto.Field( + proto.MESSAGE, + number=8, + message=data.ResponseMetaData, + ) + property_quota: data.PropertyQuota = proto.Field( + proto.MESSAGE, + number=9, + message=data.PropertyQuota, + ) + kind: str = proto.Field( + proto.STRING, + number=10, + ) + + +class RunPivotReportRequest(proto.Message): + r"""The request to generate a pivot report. + + Attributes: + property (str): + A Google Analytics GA4 property identifier whose events are + tracked. Specified in the URL path and not the body. To + learn more, see `where to find your Property + ID `__. + Within a batch request, this property should either be + unspecified or consistent with the batch-level property. + + Example: properties/1234 + dimensions (MutableSequence[google.analytics.data_v1beta.types.Dimension]): + The dimensions requested. All defined dimensions must be + used by one of the following: dimension_expression, + dimension_filter, pivots, order_bys. + metrics (MutableSequence[google.analytics.data_v1beta.types.Metric]): + The metrics requested, at least one metric needs to be + specified. All defined metrics must be used by one of the + following: metric_expression, metric_filter, order_bys. + date_ranges (MutableSequence[google.analytics.data_v1beta.types.DateRange]): + The date range to retrieve event data for the report. If + multiple date ranges are specified, event data from each + date range is used in the report. A special dimension with + field name "dateRange" can be included in a Pivot's field + names; if included, the report compares between date ranges. + In a cohort request, this ``dateRanges`` must be + unspecified. + pivots (MutableSequence[google.analytics.data_v1beta.types.Pivot]): + Describes the visual format of the report's + dimensions in columns or rows. The union of the + fieldNames (dimension names) in all pivots must + be a subset of dimension names defined in + Dimensions. No two pivots can share a dimension. + A dimension is only visible if it appears in a + pivot. + dimension_filter (google.analytics.data_v1beta.types.FilterExpression): + The filter clause of dimensions. Dimensions + must be requested to be used in this filter. + Metrics cannot be used in this filter. + metric_filter (google.analytics.data_v1beta.types.FilterExpression): + The filter clause of metrics. Applied at post + aggregation phase, similar to SQL having-clause. + Metrics must be requested to be used in this + filter. Dimensions cannot be used in this + filter. + currency_code (str): + A currency code in ISO4217 format, such as + "AED", "USD", "JPY". If the field is empty, the + report uses the property's default currency. + cohort_spec (google.analytics.data_v1beta.types.CohortSpec): + Cohort group associated with this request. If + there is a cohort group in the request the + 'cohort' dimension must be present. + keep_empty_rows (bool): + If false or unspecified, each row with all + metrics equal to 0 will not be returned. If + true, these rows will be returned if they are + not separately removed by a filter. + return_property_quota (bool): + Toggles whether to return the current state of this + Analytics Property's quota. Quota is returned in + `PropertyQuota <#PropertyQuota>`__. + """ + + property: str = proto.Field( + proto.STRING, + number=1, + ) + dimensions: MutableSequence[data.Dimension] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=data.Dimension, + ) + metrics: MutableSequence[data.Metric] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=data.Metric, + ) + date_ranges: MutableSequence[data.DateRange] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=data.DateRange, + ) + pivots: MutableSequence[data.Pivot] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=data.Pivot, + ) + dimension_filter: data.FilterExpression = proto.Field( + proto.MESSAGE, + number=6, + message=data.FilterExpression, + ) + metric_filter: data.FilterExpression = proto.Field( + proto.MESSAGE, + number=7, + message=data.FilterExpression, + ) + currency_code: str = proto.Field( + proto.STRING, + number=8, + ) + cohort_spec: data.CohortSpec = proto.Field( + proto.MESSAGE, + number=9, + message=data.CohortSpec, + ) + keep_empty_rows: bool = proto.Field( + proto.BOOL, + number=10, + ) + return_property_quota: bool = proto.Field( + proto.BOOL, + number=11, + ) + + +class RunPivotReportResponse(proto.Message): + r"""The response pivot report table corresponding to a pivot + request. + + Attributes: + pivot_headers (MutableSequence[google.analytics.data_v1beta.types.PivotHeader]): + Summarizes the columns and rows created by a pivot. Each + pivot in the request produces one header in the response. If + we have a request like this: + + :: + + "pivots": [{ + "fieldNames": ["country", + "city"] + }, + { + "fieldNames": "eventName" + }] + + We will have the following ``pivotHeaders`` in the response: + + :: + + "pivotHeaders" : [{ + "dimensionHeaders": [{ + "dimensionValues": [ + { "value": "United Kingdom" }, + { "value": "London" } + ] + }, + { + "dimensionValues": [ + { "value": "Japan" }, + { "value": "Osaka" } + ] + }] + }, + { + "dimensionHeaders": [{ + "dimensionValues": [{ "value": "session_start" }] + }, + { + "dimensionValues": [{ "value": "scroll" }] + }] + }] + dimension_headers (MutableSequence[google.analytics.data_v1beta.types.DimensionHeader]): + Describes dimension columns. The number of + DimensionHeaders and ordering of + DimensionHeaders matches the dimensions present + in rows. + metric_headers (MutableSequence[google.analytics.data_v1beta.types.MetricHeader]): + Describes metric columns. The number of + MetricHeaders and ordering of MetricHeaders + matches the metrics present in rows. + rows (MutableSequence[google.analytics.data_v1beta.types.Row]): + Rows of dimension value combinations and + metric values in the report. + aggregates (MutableSequence[google.analytics.data_v1beta.types.Row]): + Aggregation of metric values. Can be totals, minimums, or + maximums. The returned aggregations are controlled by the + metric_aggregations in the pivot. The type of aggregation + returned in each row is shown by the dimension_values which + are set to "RESERVED\_". + metadata (google.analytics.data_v1beta.types.ResponseMetaData): + Metadata for the report. + property_quota (google.analytics.data_v1beta.types.PropertyQuota): + This Analytics Property's quota state + including this request. + kind (str): + Identifies what kind of resource this message is. This + ``kind`` is always the fixed string + "analyticsData#runPivotReport". Useful to distinguish + between response types in JSON. + """ + + pivot_headers: MutableSequence[data.PivotHeader] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=data.PivotHeader, + ) + dimension_headers: MutableSequence[data.DimensionHeader] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=data.DimensionHeader, + ) + metric_headers: MutableSequence[data.MetricHeader] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=data.MetricHeader, + ) + rows: MutableSequence[data.Row] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=data.Row, + ) + aggregates: MutableSequence[data.Row] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=data.Row, + ) + metadata: data.ResponseMetaData = proto.Field( + proto.MESSAGE, + number=6, + message=data.ResponseMetaData, + ) + property_quota: data.PropertyQuota = proto.Field( + proto.MESSAGE, + number=7, + message=data.PropertyQuota, + ) + kind: str = proto.Field( + proto.STRING, + number=8, + ) + + +class BatchRunReportsRequest(proto.Message): + r"""The batch request containing multiple report requests. + + Attributes: + property (str): + A Google Analytics GA4 property identifier whose events are + tracked. Specified in the URL path and not the body. To + learn more, see `where to find your Property + ID `__. + This property must be specified for the batch. The property + within RunReportRequest may either be unspecified or + consistent with this property. + + Example: properties/1234 + requests (MutableSequence[google.analytics.data_v1beta.types.RunReportRequest]): + Individual requests. Each request has a + separate report response. Each batch request is + allowed up to 5 requests. + """ + + property: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence['RunReportRequest'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='RunReportRequest', + ) + + +class BatchRunReportsResponse(proto.Message): + r"""The batch response containing multiple reports. + + Attributes: + reports (MutableSequence[google.analytics.data_v1beta.types.RunReportResponse]): + Individual responses. Each response has a + separate report request. + kind (str): + Identifies what kind of resource this message is. This + ``kind`` is always the fixed string + "analyticsData#batchRunReports". Useful to distinguish + between response types in JSON. + """ + + reports: MutableSequence['RunReportResponse'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RunReportResponse', + ) + kind: str = proto.Field( + proto.STRING, + number=2, + ) + + +class BatchRunPivotReportsRequest(proto.Message): + r"""The batch request containing multiple pivot report requests. + + Attributes: + property (str): + A Google Analytics GA4 property identifier whose events are + tracked. Specified in the URL path and not the body. To + learn more, see `where to find your Property + ID `__. + This property must be specified for the batch. The property + within RunPivotReportRequest may either be unspecified or + consistent with this property. + + Example: properties/1234 + requests (MutableSequence[google.analytics.data_v1beta.types.RunPivotReportRequest]): + Individual requests. Each request has a + separate pivot report response. Each batch + request is allowed up to 5 requests. + """ + + property: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence['RunPivotReportRequest'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='RunPivotReportRequest', + ) + + +class BatchRunPivotReportsResponse(proto.Message): + r"""The batch response containing multiple pivot reports. + + Attributes: + pivot_reports (MutableSequence[google.analytics.data_v1beta.types.RunPivotReportResponse]): + Individual responses. Each response has a + separate pivot report request. + kind (str): + Identifies what kind of resource this message is. This + ``kind`` is always the fixed string + "analyticsData#batchRunPivotReports". Useful to distinguish + between response types in JSON. + """ + + pivot_reports: MutableSequence['RunPivotReportResponse'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RunPivotReportResponse', + ) + kind: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetMetadataRequest(proto.Message): + r"""Request for a property's dimension and metric metadata. + + Attributes: + name (str): + Required. The resource name of the metadata to retrieve. + This name field is specified in the URL path and not URL + parameters. Property is a numeric Google Analytics GA4 + Property identifier. To learn more, see `where to find your + Property + ID `__. + + Example: properties/1234/metadata + + Set the Property ID to 0 for dimensions and metrics common + to all properties. In this special mode, this method will + not return custom dimensions and metrics. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RunRealtimeReportRequest(proto.Message): + r"""The request to generate a realtime report. + + Attributes: + property (str): + A Google Analytics GA4 property identifier whose events are + tracked. Specified in the URL path and not the body. To + learn more, see `where to find your Property + ID `__. + + Example: properties/1234 + dimensions (MutableSequence[google.analytics.data_v1beta.types.Dimension]): + The dimensions requested and displayed. + metrics (MutableSequence[google.analytics.data_v1beta.types.Metric]): + The metrics requested and displayed. + dimension_filter (google.analytics.data_v1beta.types.FilterExpression): + The filter clause of dimensions. Metrics + cannot be used in this filter. + metric_filter (google.analytics.data_v1beta.types.FilterExpression): + The filter clause of metrics. Applied at post + aggregation phase, similar to SQL having-clause. + Dimensions cannot be used in this filter. + 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 can also return fewer rows than the requested + ``limit``, if there aren't as many dimension values 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. + metric_aggregations (MutableSequence[google.analytics.data_v1beta.types.MetricAggregation]): + Aggregation of metrics. Aggregated metric values will be + shown in rows where the dimension_values are set to + "RESERVED_(MetricAggregation)". + order_bys (MutableSequence[google.analytics.data_v1beta.types.OrderBy]): + Specifies how rows are ordered in the + response. + return_property_quota (bool): + Toggles whether to return the current state of this + Analytics Property's Realtime quota. Quota is returned in + `PropertyQuota <#PropertyQuota>`__. + minute_ranges (MutableSequence[google.analytics.data_v1beta.types.MinuteRange]): + The minute ranges of event data to read. If + unspecified, one minute range for the last 30 + minutes will be used. If multiple minute ranges + are requested, each response row will contain a + zero based minute range index. If two minute + ranges overlap, the event data for the + overlapping minutes is included in the response + rows for both minute ranges. + """ + + property: str = proto.Field( + proto.STRING, + number=1, + ) + dimensions: MutableSequence[data.Dimension] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=data.Dimension, + ) + metrics: MutableSequence[data.Metric] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=data.Metric, + ) + dimension_filter: data.FilterExpression = proto.Field( + proto.MESSAGE, + number=4, + message=data.FilterExpression, + ) + metric_filter: data.FilterExpression = proto.Field( + proto.MESSAGE, + number=5, + message=data.FilterExpression, + ) + limit: int = proto.Field( + proto.INT64, + number=6, + ) + metric_aggregations: MutableSequence[data.MetricAggregation] = proto.RepeatedField( + proto.ENUM, + number=7, + enum=data.MetricAggregation, + ) + order_bys: MutableSequence[data.OrderBy] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=data.OrderBy, + ) + return_property_quota: bool = proto.Field( + proto.BOOL, + number=9, + ) + minute_ranges: MutableSequence[data.MinuteRange] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=data.MinuteRange, + ) + + +class RunRealtimeReportResponse(proto.Message): + r"""The response realtime report table corresponding to a + request. + + Attributes: + dimension_headers (MutableSequence[google.analytics.data_v1beta.types.DimensionHeader]): + Describes dimension columns. The number of + DimensionHeaders and ordering of + DimensionHeaders matches the dimensions present + in rows. + metric_headers (MutableSequence[google.analytics.data_v1beta.types.MetricHeader]): + Describes metric columns. The number of + MetricHeaders and ordering of MetricHeaders + matches the metrics present in rows. + rows (MutableSequence[google.analytics.data_v1beta.types.Row]): + Rows of dimension value combinations and + metric values in the report. + totals (MutableSequence[google.analytics.data_v1beta.types.Row]): + If requested, the totaled values of metrics. + maximums (MutableSequence[google.analytics.data_v1beta.types.Row]): + If requested, the maximum values of metrics. + minimums (MutableSequence[google.analytics.data_v1beta.types.Row]): + If requested, the minimum values of metrics. + row_count (int): + The total number of rows in the query result. ``rowCount`` + is independent of the number of rows returned in the + response and the ``limit`` 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. + property_quota (google.analytics.data_v1beta.types.PropertyQuota): + This Analytics Property's Realtime quota + state including this request. + kind (str): + Identifies what kind of resource this message is. This + ``kind`` is always the fixed string + "analyticsData#runRealtimeReport". Useful to distinguish + between response types in JSON. + """ + + dimension_headers: MutableSequence[data.DimensionHeader] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=data.DimensionHeader, + ) + metric_headers: MutableSequence[data.MetricHeader] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=data.MetricHeader, + ) + rows: MutableSequence[data.Row] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=data.Row, + ) + totals: MutableSequence[data.Row] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=data.Row, + ) + maximums: MutableSequence[data.Row] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=data.Row, + ) + minimums: MutableSequence[data.Row] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=data.Row, + ) + row_count: int = proto.Field( + proto.INT32, + number=7, + ) + property_quota: data.PropertyQuota = proto.Field( + proto.MESSAGE, + number=8, + message=data.PropertyQuota, + ) + kind: str = proto.Field( + proto.STRING, + number=9, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/types/data.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/types/data.py new file mode 100644 index 0000000..9c0e869 --- /dev/null +++ b/owl-bot-staging/v1beta/google/analytics/data_v1beta/types/data.py @@ -0,0 +1,1693 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.analytics.data.v1beta', + manifest={ + 'MetricAggregation', + 'MetricType', + 'RestrictedMetricType', + 'Compatibility', + 'DateRange', + 'MinuteRange', + 'Dimension', + 'DimensionExpression', + 'Metric', + 'FilterExpression', + 'FilterExpressionList', + 'Filter', + 'OrderBy', + 'Pivot', + 'CohortSpec', + 'Cohort', + 'CohortsRange', + 'CohortReportSettings', + 'ResponseMetaData', + 'DimensionHeader', + 'MetricHeader', + 'PivotHeader', + 'PivotDimensionHeader', + 'Row', + 'DimensionValue', + 'MetricValue', + 'NumericValue', + 'PropertyQuota', + 'QuotaStatus', + 'DimensionMetadata', + 'MetricMetadata', + 'DimensionCompatibility', + 'MetricCompatibility', + }, +) + + +class MetricAggregation(proto.Enum): + r"""Represents aggregation of metrics.""" + METRIC_AGGREGATION_UNSPECIFIED = 0 + TOTAL = 1 + MINIMUM = 5 + MAXIMUM = 6 + COUNT = 4 + + +class MetricType(proto.Enum): + r"""A metric's value type.""" + METRIC_TYPE_UNSPECIFIED = 0 + TYPE_INTEGER = 1 + TYPE_FLOAT = 2 + TYPE_SECONDS = 4 + TYPE_MILLISECONDS = 5 + TYPE_MINUTES = 6 + TYPE_HOURS = 7 + TYPE_STANDARD = 8 + TYPE_CURRENCY = 9 + TYPE_FEET = 10 + TYPE_MILES = 11 + TYPE_METERS = 12 + TYPE_KILOMETERS = 13 + + +class RestrictedMetricType(proto.Enum): + r"""Categories of data that you may be restricted from viewing on + certain GA4 properties. + """ + RESTRICTED_METRIC_TYPE_UNSPECIFIED = 0 + COST_DATA = 1 + REVENUE_DATA = 2 + + +class Compatibility(proto.Enum): + r"""The compatibility types for a single dimension or metric.""" + COMPATIBILITY_UNSPECIFIED = 0 + COMPATIBLE = 1 + INCOMPATIBLE = 2 + + +class DateRange(proto.Message): + r"""A contiguous set of days: startDate, startDate + 1, ..., + endDate. Requests are allowed up to 4 date ranges. + + Attributes: + start_date (str): + The inclusive start date for the query in the format + ``YYYY-MM-DD``. Cannot be after ``end_date``. The format + ``NdaysAgo``, ``yesterday``, or ``today`` is also accepted, + and in that case, the date is inferred based on the + property's reporting time zone. + end_date (str): + The inclusive end date for the query in the format + ``YYYY-MM-DD``. Cannot be before ``start_date``. The format + ``NdaysAgo``, ``yesterday``, or ``today`` is also accepted, + and in that case, the date is inferred based on the + property's reporting time zone. + name (str): + Assigns a name to this date range. The dimension + ``dateRange`` is valued to this name in a report response. + If set, cannot begin with ``date_range_`` or ``RESERVED_``. + If not set, date ranges are named by their zero based index + in the request: ``date_range_0``, ``date_range_1``, etc. + """ + + start_date: str = proto.Field( + proto.STRING, + number=1, + ) + end_date: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + +class MinuteRange(proto.Message): + r"""A contiguous set of minutes: startMinutesAgo, startMinutesAgo + + 1, ..., endMinutesAgo. Requests are allowed up to 2 minute + ranges. + + Attributes: + start_minutes_ago (int): + The inclusive start minute for the query as a number of + minutes before now. For example, ``"startMinutesAgo": 29`` + specifies the report should include event data from 29 + minutes ago and after. Cannot be after ``endMinutesAgo``. + + If unspecified, ``startMinutesAgo`` is defaulted to 29. + Standard Analytics properties can request up to the last 30 + minutes of event data (``startMinutesAgo <= 29``), and 360 + Analytics properties can request up to the last 60 minutes + of event data (``startMinutesAgo <= 59``). + + This field is a member of `oneof`_ ``_start_minutes_ago``. + end_minutes_ago (int): + The inclusive end minute for the query as a number of + minutes before now. Cannot be before ``startMinutesAgo``. + For example, ``"endMinutesAgo": 15`` specifies the report + should include event data from prior to 15 minutes ago. + + If unspecified, ``endMinutesAgo`` is defaulted to 0. + Standard Analytics properties can request any minute in the + last 30 minutes of event data (``endMinutesAgo <= 29``), and + 360 Analytics properties can request any minute in the last + 60 minutes of event data (``endMinutesAgo <= 59``). + + This field is a member of `oneof`_ ``_end_minutes_ago``. + name (str): + Assigns a name to this minute range. The dimension + ``dateRange`` is valued to this name in a report response. + If set, cannot begin with ``date_range_`` or ``RESERVED_``. + If not set, minute ranges are named by their zero based + index in the request: ``date_range_0``, ``date_range_1``, + etc. + """ + + start_minutes_ago: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + end_minutes_ago: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + +class Dimension(proto.Message): + r"""Dimensions are attributes of your data. For example, the + dimension city indicates the city from which an event + originates. Dimension values in report responses are strings; + for example, the city could be "Paris" or "New York". Requests + are allowed up to 9 dimensions. + + Attributes: + name (str): + The name of the dimension. See the `API + Dimensions `__ + for the list of dimension names. + + If ``dimensionExpression`` is specified, ``name`` can be any + string that you would like within the allowed character set. + For example if a ``dimensionExpression`` concatenates + ``country`` and ``city``, you could call that dimension + ``countryAndCity``. Dimension names that you choose must + match the regular expression ``^[a-zA-Z0-9_]$``. + + Dimensions are referenced by ``name`` in + ``dimensionFilter``, ``orderBys``, ``dimensionExpression``, + and ``pivots``. + dimension_expression (google.analytics.data_v1beta.types.DimensionExpression): + One dimension can be the result of an + expression of multiple dimensions. For example, + dimension "country, city": concatenate(country, + ", ", city). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + dimension_expression: 'DimensionExpression' = proto.Field( + proto.MESSAGE, + number=2, + message='DimensionExpression', + ) + + +class DimensionExpression(proto.Message): + r"""Used to express a dimension which is the result of a formula of + multiple dimensions. Example usages: + + 1) lower_case(dimension) + 2) concatenate(dimension1, symbol, dimension2). + + 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: + lower_case (google.analytics.data_v1beta.types.DimensionExpression.CaseExpression): + Used to convert a dimension value to lower + case. + + This field is a member of `oneof`_ ``one_expression``. + upper_case (google.analytics.data_v1beta.types.DimensionExpression.CaseExpression): + Used to convert a dimension value to upper + case. + + This field is a member of `oneof`_ ``one_expression``. + concatenate (google.analytics.data_v1beta.types.DimensionExpression.ConcatenateExpression): + Used to combine dimension values to a single + dimension. For example, dimension "country, + city": concatenate(country, ", ", city). + + This field is a member of `oneof`_ ``one_expression``. + """ + + class CaseExpression(proto.Message): + r"""Used to convert a dimension value to a single case. + + Attributes: + dimension_name (str): + Name of a dimension. The name must refer back + to a name in dimensions field of the request. + """ + + dimension_name: str = proto.Field( + proto.STRING, + number=1, + ) + + class ConcatenateExpression(proto.Message): + r"""Used to combine dimension values to a single dimension. + + Attributes: + dimension_names (MutableSequence[str]): + Names of dimensions. The names must refer + back to names in the dimensions field of the + request. + delimiter (str): + The delimiter placed between dimension names. + + Delimiters are often single characters such as "|" or "," + but can be longer strings. If a dimension value contains the + delimiter, both will be present in response with no + distinction. For example if dimension 1 value = "US,FR", + dimension 2 value = "JP", and delimiter = ",", then the + response will contain "US,FR,JP". + """ + + dimension_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + delimiter: str = proto.Field( + proto.STRING, + number=2, + ) + + lower_case: CaseExpression = proto.Field( + proto.MESSAGE, + number=4, + oneof='one_expression', + message=CaseExpression, + ) + upper_case: CaseExpression = proto.Field( + proto.MESSAGE, + number=5, + oneof='one_expression', + message=CaseExpression, + ) + concatenate: ConcatenateExpression = proto.Field( + proto.MESSAGE, + number=6, + oneof='one_expression', + message=ConcatenateExpression, + ) + + +class Metric(proto.Message): + r"""The quantitative measurements of a report. For example, the metric + ``eventCount`` is the total number of events. Requests are allowed + up to 10 metrics. + + Attributes: + name (str): + The name of the metric. See the `API + Metrics `__ + for the list of metric names. + + If ``expression`` is specified, ``name`` can be any string + that you would like within the allowed character set. For + example if ``expression`` is ``screenPageViews/sessions``, + you could call that metric's name = ``viewsPerSession``. + Metric names that you choose must match the regular + expression ``^[a-zA-Z0-9_]$``. + + Metrics are referenced by ``name`` in ``metricFilter``, + ``orderBys``, and metric ``expression``. + expression (str): + A mathematical expression for derived metrics. For example, + the metric Event count per user is + ``eventCount/totalUsers``. + invisible (bool): + Indicates if a metric is invisible in the report response. + If a metric is invisible, the metric will not produce a + column in the response, but can be used in ``metricFilter``, + ``orderBys``, or a metric ``expression``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + expression: str = proto.Field( + proto.STRING, + number=2, + ) + invisible: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class FilterExpression(proto.Message): + r"""To express dimension or metric filters. The fields in the + same FilterExpression 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.data_v1beta.types.FilterExpressionList): + The FilterExpressions in and_group have an AND relationship. + + This field is a member of `oneof`_ ``expr``. + or_group (google.analytics.data_v1beta.types.FilterExpressionList): + The FilterExpressions in or_group have an OR relationship. + + This field is a member of `oneof`_ ``expr``. + not_expression (google.analytics.data_v1beta.types.FilterExpression): + The FilterExpression is NOT of not_expression. + + This field is a member of `oneof`_ ``expr``. + filter (google.analytics.data_v1beta.types.Filter): + 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`_ ``expr``. + """ + + and_group: 'FilterExpressionList' = proto.Field( + proto.MESSAGE, + number=1, + oneof='expr', + message='FilterExpressionList', + ) + or_group: 'FilterExpressionList' = proto.Field( + proto.MESSAGE, + number=2, + oneof='expr', + message='FilterExpressionList', + ) + not_expression: 'FilterExpression' = proto.Field( + proto.MESSAGE, + number=3, + oneof='expr', + message='FilterExpression', + ) + filter: 'Filter' = proto.Field( + proto.MESSAGE, + number=4, + oneof='expr', + message='Filter', + ) + + +class FilterExpressionList(proto.Message): + r"""A list of filter expressions. + + Attributes: + expressions (MutableSequence[google.analytics.data_v1beta.types.FilterExpression]): + A list of filter expressions. + """ + + expressions: MutableSequence['FilterExpression'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='FilterExpression', + ) + + +class Filter(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: + field_name (str): + The dimension name or metric name. + In most methods, dimensions & metrics can be + used for the first time in this field. However + in a RunPivotReportRequest, this field must be + additionally specified by name in the + RunPivotReportRequest's dimensions or metrics. + string_filter (google.analytics.data_v1beta.types.Filter.StringFilter): + Strings related filter. + + This field is a member of `oneof`_ ``one_filter``. + in_list_filter (google.analytics.data_v1beta.types.Filter.InListFilter): + A filter for in list values. + + This field is a member of `oneof`_ ``one_filter``. + numeric_filter (google.analytics.data_v1beta.types.Filter.NumericFilter): + A filter for numeric or date values. + + This field is a member of `oneof`_ ``one_filter``. + between_filter (google.analytics.data_v1beta.types.Filter.BetweenFilter): + A filter for two values. + + This field is a member of `oneof`_ ``one_filter``. + """ + + class StringFilter(proto.Message): + r"""The filter for string + + Attributes: + match_type (google.analytics.data_v1beta.types.Filter.StringFilter.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""" + MATCH_TYPE_UNSPECIFIED = 0 + EXACT = 1 + BEGINS_WITH = 2 + ENDS_WITH = 3 + CONTAINS = 4 + FULL_REGEXP = 5 + PARTIAL_REGEXP = 6 + + match_type: 'Filter.StringFilter.MatchType' = proto.Field( + proto.ENUM, + number=1, + enum='Filter.StringFilter.MatchType', + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + case_sensitive: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class InListFilter(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 NumericFilter(proto.Message): + r"""Filters for numeric or date values. + + Attributes: + operation (google.analytics.data_v1beta.types.Filter.NumericFilter.Operation): + The operation type for this filter. + value (google.analytics.data_v1beta.types.NumericValue): + A numeric value or a date value. + """ + class Operation(proto.Enum): + r"""The operation applied to a numeric filter""" + OPERATION_UNSPECIFIED = 0 + EQUAL = 1 + LESS_THAN = 2 + LESS_THAN_OR_EQUAL = 3 + GREATER_THAN = 4 + GREATER_THAN_OR_EQUAL = 5 + + operation: 'Filter.NumericFilter.Operation' = proto.Field( + proto.ENUM, + number=1, + enum='Filter.NumericFilter.Operation', + ) + value: 'NumericValue' = proto.Field( + proto.MESSAGE, + number=2, + message='NumericValue', + ) + + class BetweenFilter(proto.Message): + r"""To express that the result needs to be between two numbers + (inclusive). + + Attributes: + from_value (google.analytics.data_v1beta.types.NumericValue): + Begins with this number. + to_value (google.analytics.data_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', + ) + + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + string_filter: StringFilter = proto.Field( + proto.MESSAGE, + number=3, + oneof='one_filter', + message=StringFilter, + ) + in_list_filter: InListFilter = proto.Field( + proto.MESSAGE, + number=4, + oneof='one_filter', + message=InListFilter, + ) + numeric_filter: NumericFilter = proto.Field( + proto.MESSAGE, + number=5, + oneof='one_filter', + message=NumericFilter, + ) + between_filter: BetweenFilter = proto.Field( + proto.MESSAGE, + number=6, + oneof='one_filter', + message=BetweenFilter, + ) + + +class OrderBy(proto.Message): + r"""Order bys define how rows will be sorted in the response. For + example, ordering rows by descending event count is one + ordering, and ordering rows by the event name 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.data_v1beta.types.OrderBy.MetricOrderBy): + Sorts results by a metric's values. + + This field is a member of `oneof`_ ``one_order_by``. + dimension (google.analytics.data_v1beta.types.OrderBy.DimensionOrderBy): + Sorts results by a dimension's values. + + This field is a member of `oneof`_ ``one_order_by``. + pivot (google.analytics.data_v1beta.types.OrderBy.PivotOrderBy): + Sorts results by a metric's values within a + pivot column group. + + This field is a member of `oneof`_ ``one_order_by``. + desc (bool): + If true, sorts by descending 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.data_v1beta.types.OrderBy.DimensionOrderBy.OrderType): + Controls the rule for dimension value + ordering. + """ + class OrderType(proto.Enum): + r"""Rule to order the string dimension values by.""" + ORDER_TYPE_UNSPECIFIED = 0 + ALPHANUMERIC = 1 + CASE_INSENSITIVE_ALPHANUMERIC = 2 + NUMERIC = 3 + + dimension_name: str = proto.Field( + proto.STRING, + number=1, + ) + order_type: 'OrderBy.DimensionOrderBy.OrderType' = proto.Field( + proto.ENUM, + number=2, + enum='OrderBy.DimensionOrderBy.OrderType', + ) + + class PivotOrderBy(proto.Message): + r"""Sorts by a pivot column group. + + Attributes: + metric_name (str): + In the response to order by, order rows by + this column. Must be a metric name from the + request. + pivot_selections (MutableSequence[google.analytics.data_v1beta.types.OrderBy.PivotOrderBy.PivotSelection]): + Used to select a dimension name and value + pivot. If multiple pivot selections are given, + the sort occurs on rows where all pivot + selection dimension name and value pairs match + the row's dimension name and value pair. + """ + + class PivotSelection(proto.Message): + r"""A pair of dimension names and values. Rows with this dimension pivot + pair are ordered by the metric's value. + + For example if pivots = {{"browser", "Chrome"}} and metric_name = + "Sessions", then the rows will be sorted based on Sessions in + Chrome. + + :: + + ---------|----------|----------------|----------|---------------- + | Chrome | Chrome | Safari | Safari + ---------|----------|----------------|----------|---------------- + Country | Sessions | Pages/Sessions | Sessions | Pages/Sessions + ---------|----------|----------------|----------|---------------- + US | 2 | 2 | 3 | 1 + ---------|----------|----------------|----------|---------------- + Canada | 3 | 1 | 4 | 1 + ---------|----------|----------------|----------|---------------- + + Attributes: + dimension_name (str): + Must be a dimension name from the request. + dimension_value (str): + Order by only when the named dimension is + this value. + """ + + dimension_name: str = proto.Field( + proto.STRING, + number=1, + ) + dimension_value: str = proto.Field( + proto.STRING, + number=2, + ) + + metric_name: str = proto.Field( + proto.STRING, + number=1, + ) + pivot_selections: MutableSequence['OrderBy.PivotOrderBy.PivotSelection'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='OrderBy.PivotOrderBy.PivotSelection', + ) + + 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, + ) + pivot: PivotOrderBy = proto.Field( + proto.MESSAGE, + number=3, + oneof='one_order_by', + message=PivotOrderBy, + ) + desc: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class Pivot(proto.Message): + r"""Describes the visible dimension columns and rows in the + report response. + + Attributes: + field_names (MutableSequence[str]): + Dimension names for visible columns in the + report response. Including "dateRange" produces + a date range column; for each row in the + response, dimension values in the date range + column will indicate the corresponding date + range from the request. + order_bys (MutableSequence[google.analytics.data_v1beta.types.OrderBy]): + Specifies how dimensions are ordered in the pivot. In the + first Pivot, the OrderBys determine Row and + PivotDimensionHeader ordering; in subsequent Pivots, the + OrderBys determine only PivotDimensionHeader ordering. + Dimensions specified in these OrderBys must be a subset of + Pivot.field_names. + offset (int): + The row count of the start row. The first row + is counted as row 0. + limit (int): + The number of unique combinations of dimension values to + return in this pivot. The ``limit`` parameter is required. A + ``limit`` of 10,000 is common for single pivot requests. + + The product of the ``limit`` for each ``pivot`` in a + ``RunPivotReportRequest`` must not exceed 100,000. For + example, a two pivot request with ``limit: 1000`` in each + pivot will fail because the product is ``1,000,000``. + metric_aggregations (MutableSequence[google.analytics.data_v1beta.types.MetricAggregation]): + Aggregate the metrics by dimensions in this pivot using the + specified metric_aggregations. + """ + + field_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + order_bys: MutableSequence['OrderBy'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='OrderBy', + ) + offset: int = proto.Field( + proto.INT64, + number=3, + ) + limit: int = proto.Field( + proto.INT64, + number=4, + ) + metric_aggregations: MutableSequence['MetricAggregation'] = proto.RepeatedField( + proto.ENUM, + number=5, + enum='MetricAggregation', + ) + + +class CohortSpec(proto.Message): + r"""The specification of cohorts for a cohort report. + + Cohort reports create a time series of user retention for the + cohort. For example, you could select the cohort of users that were + acquired in the first week of September and follow that cohort for + the next six weeks. Selecting the users acquired in the first week + of September cohort is specified in the ``cohort`` object. Following + that cohort for the next six weeks is specified in the + ``cohortsRange`` object. + + For examples, see `Cohort Report + Examples `__. + + The report response could show a weekly time series where say your + app has retained 60% of this cohort after three weeks and 25% of + this cohort after six weeks. These two percentages can be calculated + by the metric ``cohortActiveUsers/cohortTotalUsers`` and will be + separate rows in the report. + + Attributes: + cohorts (MutableSequence[google.analytics.data_v1beta.types.Cohort]): + Defines the selection criteria to group users + into cohorts. + Most cohort reports define only a single cohort. + If multiple cohorts are specified, each cohort + can be recognized in the report by their name. + cohorts_range (google.analytics.data_v1beta.types.CohortsRange): + Cohort reports follow cohorts over an + extended reporting date range. This range + specifies an offset duration to follow the + cohorts over. + cohort_report_settings (google.analytics.data_v1beta.types.CohortReportSettings): + Optional settings for a cohort report. + """ + + cohorts: MutableSequence['Cohort'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Cohort', + ) + cohorts_range: 'CohortsRange' = proto.Field( + proto.MESSAGE, + number=2, + message='CohortsRange', + ) + cohort_report_settings: 'CohortReportSettings' = proto.Field( + proto.MESSAGE, + number=3, + message='CohortReportSettings', + ) + + +class Cohort(proto.Message): + r"""Defines a cohort selection criteria. A cohort is a group of users + who share a common characteristic. For example, users with the same + ``firstSessionDate`` belong to the same cohort. + + Attributes: + name (str): + Assigns a name to this cohort. The dimension ``cohort`` is + valued to this name in a report response. If set, cannot + begin with ``cohort_`` or ``RESERVED_``. If not set, cohorts + are named by their zero based index ``cohort_0``, + ``cohort_1``, etc. + dimension (str): + Dimension used by the cohort. Required and only supports + ``firstSessionDate``. + date_range (google.analytics.data_v1beta.types.DateRange): + The cohort selects users whose first touch date is between + start date and end date defined in the ``dateRange``. This + ``dateRange`` does not specify the full date range of event + data that is present in a cohort report. In a cohort report, + this ``dateRange`` is extended by the granularity and offset + present in the ``cohortsRange``; event data for the extended + reporting date range is present in a cohort report. + + In a cohort request, this ``dateRange`` is required and the + ``dateRanges`` in the ``RunReportRequest`` or + ``RunPivotReportRequest`` must be unspecified. + + This ``dateRange`` should generally be aligned with the + cohort's granularity. If ``CohortsRange`` uses daily + granularity, this ``dateRange`` can be a single day. If + ``CohortsRange`` uses weekly granularity, this ``dateRange`` + can be aligned to a week boundary, starting at Sunday and + ending Saturday. If ``CohortsRange`` uses monthly + granularity, this ``dateRange`` can be aligned to a month, + starting at the first and ending on the last day of the + month. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + dimension: str = proto.Field( + proto.STRING, + number=2, + ) + date_range: 'DateRange' = proto.Field( + proto.MESSAGE, + number=3, + message='DateRange', + ) + + +class CohortsRange(proto.Message): + r"""Configures the extended reporting date range for a cohort + report. Specifies an offset duration to follow the cohorts over. + + Attributes: + granularity (google.analytics.data_v1beta.types.CohortsRange.Granularity): + Required. The granularity used to interpret the + ``startOffset`` and ``endOffset`` for the extended reporting + date range for a cohort report. + start_offset (int): + ``startOffset`` specifies the start date of the extended + reporting date range for a cohort report. ``startOffset`` is + commonly set to 0 so that reports contain data from the + acquisition of the cohort forward. + + If ``granularity`` is ``DAILY``, the ``startDate`` of the + extended reporting date range is ``startDate`` of the cohort + plus ``startOffset`` days. + + If ``granularity`` is ``WEEKLY``, the ``startDate`` of the + extended reporting date range is ``startDate`` of the cohort + plus ``startOffset * 7`` days. + + If ``granularity`` is ``MONTHLY``, the ``startDate`` of the + extended reporting date range is ``startDate`` of the cohort + plus ``startOffset * 30`` days. + end_offset (int): + Required. ``endOffset`` specifies the end date of the + extended reporting date range for a cohort report. + ``endOffset`` can be any positive integer but is commonly + set to 5 to 10 so that reports contain data on the cohort + for the next several granularity time periods. + + If ``granularity`` is ``DAILY``, the ``endDate`` of the + extended reporting date range is ``endDate`` of the cohort + plus ``endOffset`` days. + + If ``granularity`` is ``WEEKLY``, the ``endDate`` of the + extended reporting date range is ``endDate`` of the cohort + plus ``endOffset * 7`` days. + + If ``granularity`` is ``MONTHLY``, the ``endDate`` of the + extended reporting date range is ``endDate`` of the cohort + plus ``endOffset * 30`` days. + """ + class Granularity(proto.Enum): + r"""The granularity used to interpret the ``startOffset`` and + ``endOffset`` for the extended reporting date range for a cohort + report. + """ + GRANULARITY_UNSPECIFIED = 0 + DAILY = 1 + WEEKLY = 2 + MONTHLY = 3 + + granularity: Granularity = proto.Field( + proto.ENUM, + number=1, + enum=Granularity, + ) + start_offset: int = proto.Field( + proto.INT32, + number=2, + ) + end_offset: int = proto.Field( + proto.INT32, + number=3, + ) + + +class CohortReportSettings(proto.Message): + r"""Optional settings of a cohort report. + + Attributes: + accumulate (bool): + If true, accumulates the result from first touch day to the + end day. Not supported in ``RunReportRequest``. + """ + + accumulate: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +class ResponseMetaData(proto.Message): + r"""Response's metadata carrying additional information about the + report content. + + Attributes: + data_loss_from_other_row (bool): + If true, indicates some buckets of dimension + combinations are rolled into "(other)" row. This + can happen for high cardinality reports. + schema_restriction_response (google.analytics.data_v1beta.types.ResponseMetaData.SchemaRestrictionResponse): + Describes the schema restrictions actively enforced in + creating this report. To learn more, see `Access and + data-restriction + management `__. + + This field is a member of `oneof`_ ``_schema_restriction_response``. + currency_code (str): + The currency code used in this report. Intended to be used + in formatting currency metrics like ``purchaseRevenue`` for + visualization. If currency_code was specified in the + request, this response parameter will echo the request + parameter; otherwise, this response parameter is the + property's current currency_code. + + Currency codes are string encodings of currency types from + the ISO 4217 standard + (https://en.wikipedia.org/wiki/ISO_4217); for example "USD", + "EUR", "JPY". To learn more, see + https://support.google.com/analytics/answer/9796179. + + This field is a member of `oneof`_ ``_currency_code``. + time_zone (str): + The property's current timezone. Intended to be used to + interpret time-based dimensions like ``hour`` and + ``minute``. Formatted as strings from the IANA Time Zone + database (https://www.iana.org/time-zones); for example + "America/New_York" or "Asia/Tokyo". + + This field is a member of `oneof`_ ``_time_zone``. + empty_reason (str): + If empty reason is specified, the report is + empty for this reason. + + This field is a member of `oneof`_ ``_empty_reason``. + subject_to_thresholding (bool): + If ``subjectToThresholding`` is true, this report is subject + to thresholding and only returns data that meets the minimum + aggregation thresholds. It is possible for a request to be + subject to thresholding thresholding and no data is absent + from the report, and this happens when all data is above the + thresholds. To learn more, see `Data + thresholds `__ + and `About Demographics and + Interests `__. + + This field is a member of `oneof`_ ``_subject_to_thresholding``. + """ + + class SchemaRestrictionResponse(proto.Message): + r"""The schema restrictions actively enforced in creating this report. + To learn more, see `Access and data-restriction + management `__. + + Attributes: + active_metric_restrictions (MutableSequence[google.analytics.data_v1beta.types.ResponseMetaData.SchemaRestrictionResponse.ActiveMetricRestriction]): + All restrictions actively enforced in creating the report. + For example, ``purchaseRevenue`` always has the restriction + type ``REVENUE_DATA``. However, this active response + restriction is only populated if the user's custom role + disallows access to ``REVENUE_DATA``. + """ + + class ActiveMetricRestriction(proto.Message): + r"""A metric actively restricted in creating the report. + + Attributes: + metric_name (str): + The name of the restricted metric. + + This field is a member of `oneof`_ ``_metric_name``. + restricted_metric_types (MutableSequence[google.analytics.data_v1beta.types.RestrictedMetricType]): + The reason for this metric's restriction. + """ + + metric_name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + restricted_metric_types: MutableSequence['RestrictedMetricType'] = proto.RepeatedField( + proto.ENUM, + number=2, + enum='RestrictedMetricType', + ) + + active_metric_restrictions: MutableSequence['ResponseMetaData.SchemaRestrictionResponse.ActiveMetricRestriction'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ResponseMetaData.SchemaRestrictionResponse.ActiveMetricRestriction', + ) + + data_loss_from_other_row: bool = proto.Field( + proto.BOOL, + number=3, + ) + schema_restriction_response: SchemaRestrictionResponse = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message=SchemaRestrictionResponse, + ) + currency_code: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + time_zone: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + empty_reason: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + subject_to_thresholding: bool = proto.Field( + proto.BOOL, + number=8, + optional=True, + ) + + +class DimensionHeader(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: + name (str): + The dimension's name. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class MetricHeader(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: + name (str): + The metric's name. + type_ (google.analytics.data_v1beta.types.MetricType): + The metric's data type. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: 'MetricType' = proto.Field( + proto.ENUM, + number=2, + enum='MetricType', + ) + + +class PivotHeader(proto.Message): + r"""Dimensions' values in a single pivot. + + Attributes: + pivot_dimension_headers (MutableSequence[google.analytics.data_v1beta.types.PivotDimensionHeader]): + The size is the same as the cardinality of + the corresponding dimension combinations. + row_count (int): + The cardinality of the pivot. The total number of rows for + this pivot's fields regardless of how the parameters + ``offset`` and ``limit`` are specified in the request. + """ + + pivot_dimension_headers: MutableSequence['PivotDimensionHeader'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='PivotDimensionHeader', + ) + row_count: int = proto.Field( + proto.INT32, + number=2, + ) + + +class PivotDimensionHeader(proto.Message): + r"""Summarizes dimension values from a row for this pivot. + + Attributes: + dimension_values (MutableSequence[google.analytics.data_v1beta.types.DimensionValue]): + Values of multiple dimensions in a pivot. + """ + + dimension_values: MutableSequence['DimensionValue'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='DimensionValue', + ) + + +class Row(proto.Message): + r"""Report data for each row. For example if RunReportRequest contains: + + .. code:: none + + "dimensions": [ + { + "name": "eventName" + }, + { + "name": "countryId" + } + ], + "metrics": [ + { + "name": "eventCount" + } + ] + + One row with 'in_app_purchase' as the eventName, 'JP' as the + countryId, and 15 as the eventCount, would be: + + .. code:: none + + "dimensionValues": [ + { + "value": "in_app_purchase" + }, + { + "value": "JP" + } + ], + "metricValues": [ + { + "value": "15" + } + ] + + Attributes: + dimension_values (MutableSequence[google.analytics.data_v1beta.types.DimensionValue]): + List of requested dimension values. In a PivotReport, + dimension_values are only listed for dimensions included in + a pivot. + metric_values (MutableSequence[google.analytics.data_v1beta.types.MetricValue]): + List of requested visible metric values. + """ + + dimension_values: MutableSequence['DimensionValue'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='DimensionValue', + ) + metric_values: MutableSequence['MetricValue'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='MetricValue', + ) + + +class DimensionValue(proto.Message): + r"""The value of a dimension. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (str): + Value as a string if the dimension type is a + string. + + This field is a member of `oneof`_ ``one_value``. + """ + + value: str = proto.Field( + proto.STRING, + number=1, + oneof='one_value', + ) + + +class MetricValue(proto.Message): + r"""The value of a metric. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (str): + Measurement value. See MetricHeader for type. + + This field is a member of `oneof`_ ``one_value``. + """ + + value: str = proto.Field( + proto.STRING, + number=4, + oneof='one_value', + ) + + +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 PropertyQuota(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.data_v1beta.types.QuotaStatus): + Standard Analytics Properties can use up to + 25,000 tokens per day; Analytics 360 Properties + can use 250,000 tokens per day. Most requests + consume fewer than 10 tokens. + tokens_per_hour (google.analytics.data_v1beta.types.QuotaStatus): + Standard Analytics Properties can use up to + 5,000 tokens per hour; Analytics 360 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.data_v1beta.types.QuotaStatus): + Standard Analytics Properties can send up to + 10 concurrent requests; Analytics 360 Properties + can use up to 50 concurrent requests. + server_errors_per_project_per_hour (google.analytics.data_v1beta.types.QuotaStatus): + Standard Analytics Properties and cloud + project pairs can have up to 10 server errors + per hour; Analytics 360 Properties and cloud + project pairs can have up to 50 server errors + per hour. + potentially_thresholded_requests_per_hour (google.analytics.data_v1beta.types.QuotaStatus): + Analytics Properties can send up to 120 + requests with potentially thresholded dimensions + per hour. In a batch request, each report + request is individually counted for this quota + if the request contains potentially thresholded + dimensions. + tokens_per_project_per_hour (google.analytics.data_v1beta.types.QuotaStatus): + Analytics Properties can use up to 25% of + their tokens per project per hour. This amounts + to standard Analytics Properties can use up to + 1,250 tokens per project per hour, and 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: 'QuotaStatus' = proto.Field( + proto.MESSAGE, + number=1, + message='QuotaStatus', + ) + tokens_per_hour: 'QuotaStatus' = proto.Field( + proto.MESSAGE, + number=2, + message='QuotaStatus', + ) + concurrent_requests: 'QuotaStatus' = proto.Field( + proto.MESSAGE, + number=3, + message='QuotaStatus', + ) + server_errors_per_project_per_hour: 'QuotaStatus' = proto.Field( + proto.MESSAGE, + number=4, + message='QuotaStatus', + ) + potentially_thresholded_requests_per_hour: 'QuotaStatus' = proto.Field( + proto.MESSAGE, + number=5, + message='QuotaStatus', + ) + tokens_per_project_per_hour: 'QuotaStatus' = proto.Field( + proto.MESSAGE, + number=6, + message='QuotaStatus', + ) + + +class QuotaStatus(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, + ) + + +class DimensionMetadata(proto.Message): + r"""Explains a dimension. + + Attributes: + api_name (str): + This dimension's name. Useable in + `Dimension <#Dimension>`__'s ``name``. For example, + ``eventName``. + ui_name (str): + This dimension's name within the Google Analytics user + interface. For example, ``Event name``. + description (str): + Description of how this dimension is used and + calculated. + deprecated_api_names (MutableSequence[str]): + Still usable but deprecated names for this dimension. If + populated, this dimension is available by either ``apiName`` + or one of ``deprecatedApiNames`` for a period of time. After + the deprecation period, the dimension will be available only + by ``apiName``. + custom_definition (bool): + True if the dimension is a custom dimension + for this property. + category (str): + The display name of the category that this + dimension belongs to. Similar dimensions and + metrics are categorized together. + """ + + api_name: str = proto.Field( + proto.STRING, + number=1, + ) + ui_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + deprecated_api_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + custom_definition: bool = proto.Field( + proto.BOOL, + number=5, + ) + category: str = proto.Field( + proto.STRING, + number=7, + ) + + +class MetricMetadata(proto.Message): + r"""Explains a metric. + + Attributes: + api_name (str): + A metric name. Useable in `Metric <#Metric>`__'s ``name``. + For example, ``eventCount``. + ui_name (str): + This metric's name within the Google Analytics user + interface. For example, ``Event count``. + description (str): + Description of how this metric is used and + calculated. + deprecated_api_names (MutableSequence[str]): + Still usable but deprecated names for this metric. If + populated, this metric is available by either ``apiName`` or + one of ``deprecatedApiNames`` for a period of time. After + the deprecation period, the metric will be available only by + ``apiName``. + type_ (google.analytics.data_v1beta.types.MetricType): + The type of this metric. + expression (str): + The mathematical expression for this derived metric. Can be + used in `Metric <#Metric>`__'s ``expression`` field for + equivalent reports. Most metrics are not expressions, and + for non-expressions, this field is empty. + custom_definition (bool): + True if the metric is a custom metric for + this property. + blocked_reasons (MutableSequence[google.analytics.data_v1beta.types.MetricMetadata.BlockedReason]): + If reasons are specified, your access is blocked to this + metric for this property. API requests from you to this + property for this metric will succeed; however, the report + will contain only zeros for this metric. API requests with + metric filters on blocked metrics will fail. If reasons are + empty, you have access to this metric. + + To learn more, see `Access and data-restriction + management `__. + category (str): + The display name of the category that this + metrics belongs to. Similar dimensions and + metrics are categorized together. + """ + class BlockedReason(proto.Enum): + r"""Justifications for why this metric is blocked.""" + BLOCKED_REASON_UNSPECIFIED = 0 + NO_REVENUE_METRICS = 1 + NO_COST_METRICS = 2 + + api_name: str = proto.Field( + proto.STRING, + number=1, + ) + ui_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + deprecated_api_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + type_: 'MetricType' = proto.Field( + proto.ENUM, + number=5, + enum='MetricType', + ) + expression: str = proto.Field( + proto.STRING, + number=6, + ) + custom_definition: bool = proto.Field( + proto.BOOL, + number=7, + ) + blocked_reasons: MutableSequence[BlockedReason] = proto.RepeatedField( + proto.ENUM, + number=8, + enum=BlockedReason, + ) + category: str = proto.Field( + proto.STRING, + number=10, + ) + + +class DimensionCompatibility(proto.Message): + r"""The compatibility for a single dimension. + + Attributes: + dimension_metadata (google.analytics.data_v1beta.types.DimensionMetadata): + The dimension metadata contains the API name + for this compatibility information. The + dimension metadata also contains other helpful + information like the UI name and description. + + This field is a member of `oneof`_ ``_dimension_metadata``. + compatibility (google.analytics.data_v1beta.types.Compatibility): + The compatibility of this dimension. If the + compatibility is COMPATIBLE, this dimension can + be successfully added to the report. + + This field is a member of `oneof`_ ``_compatibility``. + """ + + dimension_metadata: 'DimensionMetadata' = proto.Field( + proto.MESSAGE, + number=1, + optional=True, + message='DimensionMetadata', + ) + compatibility: 'Compatibility' = proto.Field( + proto.ENUM, + number=2, + optional=True, + enum='Compatibility', + ) + + +class MetricCompatibility(proto.Message): + r"""The compatibility for a single metric. + + Attributes: + metric_metadata (google.analytics.data_v1beta.types.MetricMetadata): + The metric metadata contains the API name for + this compatibility information. The metric + metadata also contains other helpful information + like the UI name and description. + + This field is a member of `oneof`_ ``_metric_metadata``. + compatibility (google.analytics.data_v1beta.types.Compatibility): + The compatibility of this metric. If the + compatibility is COMPATIBLE, this metric can be + successfully added to the report. + + This field is a member of `oneof`_ ``_compatibility``. + """ + + metric_metadata: 'MetricMetadata' = proto.Field( + proto.MESSAGE, + number=1, + optional=True, + message='MetricMetadata', + ) + compatibility: 'Compatibility' = proto.Field( + proto.ENUM, + number=2, + optional=True, + enum='Compatibility', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/mypy.ini b/owl-bot-staging/v1beta/mypy.ini new file mode 100644 index 0000000..574c5ae --- /dev/null +++ b/owl-bot-staging/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1beta/noxfile.py b/owl-bot-staging/v1beta/noxfile.py new file mode 100644 index 0000000..4a0d334 --- /dev/null +++ b/owl-bot-staging/v1beta/noxfile.py @@ -0,0 +1,179 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.10" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/analytics/data_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.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, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_async.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_async.py new file mode 100644 index 0000000..7478f56 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchRunPivotReports +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-data + + +# [START analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 data_v1beta + + +async def sample_batch_run_pivot_reports(): + # Create a client + client = data_v1beta.BetaAnalyticsDataAsyncClient() + + # Initialize request argument(s) + request = data_v1beta.BatchRunPivotReportsRequest( + ) + + # Make the request + response = await client.batch_run_pivot_reports(request=request) + + # Handle the response + print(response) + +# [END analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_sync.py new file mode 100644 index 0000000..e41ff39 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchRunPivotReports +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-data + + +# [START analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 data_v1beta + + +def sample_batch_run_pivot_reports(): + # Create a client + client = data_v1beta.BetaAnalyticsDataClient() + + # Initialize request argument(s) + request = data_v1beta.BatchRunPivotReportsRequest( + ) + + # Make the request + response = client.batch_run_pivot_reports(request=request) + + # Handle the response + print(response) + +# [END analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_async.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_async.py new file mode 100644 index 0000000..4d3970d --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchRunReports +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-data + + +# [START analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunReports_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 data_v1beta + + +async def sample_batch_run_reports(): + # Create a client + client = data_v1beta.BetaAnalyticsDataAsyncClient() + + # Initialize request argument(s) + request = data_v1beta.BatchRunReportsRequest( + ) + + # Make the request + response = await client.batch_run_reports(request=request) + + # Handle the response + print(response) + +# [END analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunReports_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_sync.py new file mode 100644 index 0000000..dd30901 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchRunReports +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-data + + +# [START analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunReports_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 data_v1beta + + +def sample_batch_run_reports(): + # Create a client + client = data_v1beta.BetaAnalyticsDataClient() + + # Initialize request argument(s) + request = data_v1beta.BatchRunReportsRequest( + ) + + # Make the request + response = client.batch_run_reports(request=request) + + # Handle the response + print(response) + +# [END analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunReports_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_async.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_async.py new file mode 100644 index 0000000..13ca3bf --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CheckCompatibility +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-data + + +# [START analyticsdata_v1beta_generated_BetaAnalyticsData_CheckCompatibility_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 data_v1beta + + +async def sample_check_compatibility(): + # Create a client + client = data_v1beta.BetaAnalyticsDataAsyncClient() + + # Initialize request argument(s) + request = data_v1beta.CheckCompatibilityRequest( + ) + + # Make the request + response = await client.check_compatibility(request=request) + + # Handle the response + print(response) + +# [END analyticsdata_v1beta_generated_BetaAnalyticsData_CheckCompatibility_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_sync.py new file mode 100644 index 0000000..b1a62c0 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CheckCompatibility +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-data + + +# [START analyticsdata_v1beta_generated_BetaAnalyticsData_CheckCompatibility_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 data_v1beta + + +def sample_check_compatibility(): + # Create a client + client = data_v1beta.BetaAnalyticsDataClient() + + # Initialize request argument(s) + request = data_v1beta.CheckCompatibilityRequest( + ) + + # Make the request + response = client.check_compatibility(request=request) + + # Handle the response + print(response) + +# [END analyticsdata_v1beta_generated_BetaAnalyticsData_CheckCompatibility_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_async.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_async.py new file mode 100644 index 0000000..f450aed --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMetadata +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-data + + +# [START analyticsdata_v1beta_generated_BetaAnalyticsData_GetMetadata_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 data_v1beta + + +async def sample_get_metadata(): + # Create a client + client = data_v1beta.BetaAnalyticsDataAsyncClient() + + # Initialize request argument(s) + request = data_v1beta.GetMetadataRequest( + name="name_value", + ) + + # Make the request + response = await client.get_metadata(request=request) + + # Handle the response + print(response) + +# [END analyticsdata_v1beta_generated_BetaAnalyticsData_GetMetadata_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_sync.py new file mode 100644 index 0000000..a331017 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMetadata +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-data + + +# [START analyticsdata_v1beta_generated_BetaAnalyticsData_GetMetadata_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 data_v1beta + + +def sample_get_metadata(): + # Create a client + client = data_v1beta.BetaAnalyticsDataClient() + + # Initialize request argument(s) + request = data_v1beta.GetMetadataRequest( + name="name_value", + ) + + # Make the request + response = client.get_metadata(request=request) + + # Handle the response + print(response) + +# [END analyticsdata_v1beta_generated_BetaAnalyticsData_GetMetadata_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_async.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_async.py new file mode 100644 index 0000000..895037a --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RunPivotReport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-data + + +# [START analyticsdata_v1beta_generated_BetaAnalyticsData_RunPivotReport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 data_v1beta + + +async def sample_run_pivot_report(): + # Create a client + client = data_v1beta.BetaAnalyticsDataAsyncClient() + + # Initialize request argument(s) + request = data_v1beta.RunPivotReportRequest( + ) + + # Make the request + response = await client.run_pivot_report(request=request) + + # Handle the response + print(response) + +# [END analyticsdata_v1beta_generated_BetaAnalyticsData_RunPivotReport_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_sync.py new file mode 100644 index 0000000..20a0574 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RunPivotReport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-data + + +# [START analyticsdata_v1beta_generated_BetaAnalyticsData_RunPivotReport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 data_v1beta + + +def sample_run_pivot_report(): + # Create a client + client = data_v1beta.BetaAnalyticsDataClient() + + # Initialize request argument(s) + request = data_v1beta.RunPivotReportRequest( + ) + + # Make the request + response = client.run_pivot_report(request=request) + + # Handle the response + print(response) + +# [END analyticsdata_v1beta_generated_BetaAnalyticsData_RunPivotReport_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_async.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_async.py new file mode 100644 index 0000000..ac1f54d --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RunRealtimeReport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-data + + +# [START analyticsdata_v1beta_generated_BetaAnalyticsData_RunRealtimeReport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 data_v1beta + + +async def sample_run_realtime_report(): + # Create a client + client = data_v1beta.BetaAnalyticsDataAsyncClient() + + # Initialize request argument(s) + request = data_v1beta.RunRealtimeReportRequest( + ) + + # Make the request + response = await client.run_realtime_report(request=request) + + # Handle the response + print(response) + +# [END analyticsdata_v1beta_generated_BetaAnalyticsData_RunRealtimeReport_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_sync.py new file mode 100644 index 0000000..5985bb1 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RunRealtimeReport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-data + + +# [START analyticsdata_v1beta_generated_BetaAnalyticsData_RunRealtimeReport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 data_v1beta + + +def sample_run_realtime_report(): + # Create a client + client = data_v1beta.BetaAnalyticsDataClient() + + # Initialize request argument(s) + request = data_v1beta.RunRealtimeReportRequest( + ) + + # Make the request + response = client.run_realtime_report(request=request) + + # Handle the response + print(response) + +# [END analyticsdata_v1beta_generated_BetaAnalyticsData_RunRealtimeReport_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_report_async.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_report_async.py new file mode 100644 index 0000000..df56098 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_report_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RunReport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-data + + +# [START analyticsdata_v1beta_generated_BetaAnalyticsData_RunReport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 data_v1beta + + +async def sample_run_report(): + # Create a client + client = data_v1beta.BetaAnalyticsDataAsyncClient() + + # Initialize request argument(s) + request = data_v1beta.RunReportRequest( + ) + + # Make the request + response = await client.run_report(request=request) + + # Handle the response + print(response) + +# [END analyticsdata_v1beta_generated_BetaAnalyticsData_RunReport_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_report_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_report_sync.py new file mode 100644 index 0000000..4dbf6eb --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_report_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RunReport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-data + + +# [START analyticsdata_v1beta_generated_BetaAnalyticsData_RunReport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require 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 data_v1beta + + +def sample_run_report(): + # Create a client + client = data_v1beta.BetaAnalyticsDataClient() + + # Initialize request argument(s) + request = data_v1beta.RunReportRequest( + ) + + # Make the request + response = client.run_report(request=request) + + # Handle the response + print(response) + +# [END analyticsdata_v1beta_generated_BetaAnalyticsData_RunReport_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json b/owl-bot-staging/v1beta/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json new file mode 100644 index 0000000..b945bac --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json @@ -0,0 +1,1094 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.analytics.data.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-analytics-data", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient", + "shortName": "BetaAnalyticsDataAsyncClient" + }, + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient.batch_run_pivot_reports", + "method": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.BatchRunPivotReports", + "service": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", + "shortName": "BetaAnalyticsData" + }, + "shortName": "BatchRunPivotReports" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.data_v1beta.types.BatchRunPivotReportsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.data_v1beta.types.BatchRunPivotReportsResponse", + "shortName": "batch_run_pivot_reports" + }, + "description": "Sample for BatchRunPivotReports", + "file": "analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_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": "analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient", + "shortName": "BetaAnalyticsDataClient" + }, + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient.batch_run_pivot_reports", + "method": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.BatchRunPivotReports", + "service": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", + "shortName": "BetaAnalyticsData" + }, + "shortName": "BatchRunPivotReports" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.data_v1beta.types.BatchRunPivotReportsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.data_v1beta.types.BatchRunPivotReportsResponse", + "shortName": "batch_run_pivot_reports" + }, + "description": "Sample for BatchRunPivotReports", + "file": "analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_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": "analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient", + "shortName": "BetaAnalyticsDataAsyncClient" + }, + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient.batch_run_reports", + "method": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.BatchRunReports", + "service": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", + "shortName": "BetaAnalyticsData" + }, + "shortName": "BatchRunReports" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.data_v1beta.types.BatchRunReportsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.data_v1beta.types.BatchRunReportsResponse", + "shortName": "batch_run_reports" + }, + "description": "Sample for BatchRunReports", + "file": "analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunReports_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": "analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient", + "shortName": "BetaAnalyticsDataClient" + }, + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient.batch_run_reports", + "method": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.BatchRunReports", + "service": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", + "shortName": "BetaAnalyticsData" + }, + "shortName": "BatchRunReports" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.data_v1beta.types.BatchRunReportsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.data_v1beta.types.BatchRunReportsResponse", + "shortName": "batch_run_reports" + }, + "description": "Sample for BatchRunReports", + "file": "analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunReports_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": "analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient", + "shortName": "BetaAnalyticsDataAsyncClient" + }, + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient.check_compatibility", + "method": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.CheckCompatibility", + "service": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", + "shortName": "BetaAnalyticsData" + }, + "shortName": "CheckCompatibility" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.data_v1beta.types.CheckCompatibilityRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.data_v1beta.types.CheckCompatibilityResponse", + "shortName": "check_compatibility" + }, + "description": "Sample for CheckCompatibility", + "file": "analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_CheckCompatibility_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": "analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient", + "shortName": "BetaAnalyticsDataClient" + }, + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient.check_compatibility", + "method": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.CheckCompatibility", + "service": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", + "shortName": "BetaAnalyticsData" + }, + "shortName": "CheckCompatibility" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.data_v1beta.types.CheckCompatibilityRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.data_v1beta.types.CheckCompatibilityResponse", + "shortName": "check_compatibility" + }, + "description": "Sample for CheckCompatibility", + "file": "analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_CheckCompatibility_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": "analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient", + "shortName": "BetaAnalyticsDataAsyncClient" + }, + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient.get_metadata", + "method": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.GetMetadata", + "service": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", + "shortName": "BetaAnalyticsData" + }, + "shortName": "GetMetadata" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.data_v1beta.types.GetMetadataRequest" + }, + { + "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.data_v1beta.types.Metadata", + "shortName": "get_metadata" + }, + "description": "Sample for GetMetadata", + "file": "analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_GetMetadata_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": "analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient", + "shortName": "BetaAnalyticsDataClient" + }, + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient.get_metadata", + "method": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.GetMetadata", + "service": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", + "shortName": "BetaAnalyticsData" + }, + "shortName": "GetMetadata" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.data_v1beta.types.GetMetadataRequest" + }, + { + "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.data_v1beta.types.Metadata", + "shortName": "get_metadata" + }, + "description": "Sample for GetMetadata", + "file": "analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_GetMetadata_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": "analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient", + "shortName": "BetaAnalyticsDataAsyncClient" + }, + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient.run_pivot_report", + "method": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.RunPivotReport", + "service": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", + "shortName": "BetaAnalyticsData" + }, + "shortName": "RunPivotReport" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.data_v1beta.types.RunPivotReportRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.data_v1beta.types.RunPivotReportResponse", + "shortName": "run_pivot_report" + }, + "description": "Sample for RunPivotReport", + "file": "analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_RunPivotReport_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": "analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient", + "shortName": "BetaAnalyticsDataClient" + }, + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient.run_pivot_report", + "method": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.RunPivotReport", + "service": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", + "shortName": "BetaAnalyticsData" + }, + "shortName": "RunPivotReport" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.data_v1beta.types.RunPivotReportRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.data_v1beta.types.RunPivotReportResponse", + "shortName": "run_pivot_report" + }, + "description": "Sample for RunPivotReport", + "file": "analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_RunPivotReport_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": "analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient", + "shortName": "BetaAnalyticsDataAsyncClient" + }, + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient.run_realtime_report", + "method": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.RunRealtimeReport", + "service": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", + "shortName": "BetaAnalyticsData" + }, + "shortName": "RunRealtimeReport" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.data_v1beta.types.RunRealtimeReportRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.data_v1beta.types.RunRealtimeReportResponse", + "shortName": "run_realtime_report" + }, + "description": "Sample for RunRealtimeReport", + "file": "analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_RunRealtimeReport_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": "analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient", + "shortName": "BetaAnalyticsDataClient" + }, + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient.run_realtime_report", + "method": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.RunRealtimeReport", + "service": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", + "shortName": "BetaAnalyticsData" + }, + "shortName": "RunRealtimeReport" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.data_v1beta.types.RunRealtimeReportRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.data_v1beta.types.RunRealtimeReportResponse", + "shortName": "run_realtime_report" + }, + "description": "Sample for RunRealtimeReport", + "file": "analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_RunRealtimeReport_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": "analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient", + "shortName": "BetaAnalyticsDataAsyncClient" + }, + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient.run_report", + "method": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.RunReport", + "service": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", + "shortName": "BetaAnalyticsData" + }, + "shortName": "RunReport" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.data_v1beta.types.RunReportRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.data_v1beta.types.RunReportResponse", + "shortName": "run_report" + }, + "description": "Sample for RunReport", + "file": "analyticsdata_v1beta_generated_beta_analytics_data_run_report_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_RunReport_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": "analyticsdata_v1beta_generated_beta_analytics_data_run_report_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient", + "shortName": "BetaAnalyticsDataClient" + }, + "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient.run_report", + "method": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.RunReport", + "service": { + "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", + "shortName": "BetaAnalyticsData" + }, + "shortName": "RunReport" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.data_v1beta.types.RunReportRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.data_v1beta.types.RunReportResponse", + "shortName": "run_report" + }, + "description": "Sample for RunReport", + "file": "analyticsdata_v1beta_generated_beta_analytics_data_run_report_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_RunReport_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": "analyticsdata_v1beta_generated_beta_analytics_data_run_report_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1beta/scripts/fixup_data_v1beta_keywords.py b/owl-bot-staging/v1beta/scripts/fixup_data_v1beta_keywords.py new file mode 100644 index 0000000..3f3b1da --- /dev/null +++ b/owl-bot-staging/v1beta/scripts/fixup_data_v1beta_keywords.py @@ -0,0 +1,182 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 dataCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_run_pivot_reports': ('property', 'requests', ), + 'batch_run_reports': ('property', 'requests', ), + 'check_compatibility': ('property', 'dimensions', 'metrics', 'dimension_filter', 'metric_filter', 'compatibility_filter', ), + 'get_metadata': ('name', ), + 'run_pivot_report': ('property', 'dimensions', 'metrics', 'date_ranges', 'pivots', 'dimension_filter', 'metric_filter', 'currency_code', 'cohort_spec', 'keep_empty_rows', 'return_property_quota', ), + 'run_realtime_report': ('property', 'dimensions', 'metrics', 'dimension_filter', 'metric_filter', 'limit', 'metric_aggregations', 'order_bys', 'return_property_quota', 'minute_ranges', ), + 'run_report': ('property', 'dimensions', 'metrics', 'date_ranges', 'dimension_filter', 'metric_filter', 'offset', 'limit', 'metric_aggregations', 'order_bys', 'currency_code', 'cohort_spec', 'keep_empty_rows', 'return_property_quota', ), + } + + 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=dataCallTransformer(), +): + """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 data 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/v1beta/setup.py b/owl-bot-staging/v1beta/setup.py new file mode 100644 index 0000000..6563668 --- /dev/null +++ b/owl-bot-staging/v1beta/setup.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-analytics-data' + + +description = "Google Analytics Data API client library" + +version = {} +with open(os.path.join(package_root, 'google/analytics/data/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.33.2, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-google-analytics-data" + +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.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google"] +if "google.cloud" in packages: + namespaces.append("google.cloud") + +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", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/v1beta/testing/constraints-3.10.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/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/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/v1beta/testing/constraints-3.11.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/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/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/v1beta/testing/constraints-3.7.txt new file mode 100644 index 0000000..aca9f2d --- /dev/null +++ b/owl-bot-staging/v1beta/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +# This file is intentionally left empty to test the +# latest versions of dependencies. +google-api-core==1.33.2 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/v1beta/testing/constraints-3.8.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/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/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/v1beta/testing/constraints-3.9.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/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/v1beta/tests/__init__.py b/owl-bot-staging/v1beta/tests/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1beta/tests/unit/__init__.py b/owl-bot-staging/v1beta/tests/unit/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1beta/tests/unit/gapic/data_v1beta/__init__.py b/owl-bot-staging/v1beta/tests/unit/gapic/data_v1beta/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1beta/tests/unit/gapic/data_v1beta/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1beta/tests/unit/gapic/data_v1beta/test_beta_analytics_data.py b/owl-bot-staging/v1beta/tests/unit/gapic/data_v1beta/test_beta_analytics_data.py new file mode 100644 index 0000000..300141e --- /dev/null +++ b/owl-bot-staging/v1beta/tests/unit/gapic/data_v1beta/test_beta_analytics_data.py @@ -0,0 +1,3230 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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.data_v1beta.services.beta_analytics_data import BetaAnalyticsDataAsyncClient +from google.analytics.data_v1beta.services.beta_analytics_data import BetaAnalyticsDataClient +from google.analytics.data_v1beta.services.beta_analytics_data import transports +from google.analytics.data_v1beta.types import analytics_data_api +from google.analytics.data_v1beta.types import data +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +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 BetaAnalyticsDataClient._get_default_mtls_endpoint(None) is None + assert BetaAnalyticsDataClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert BetaAnalyticsDataClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert BetaAnalyticsDataClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert BetaAnalyticsDataClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert BetaAnalyticsDataClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (BetaAnalyticsDataClient, "grpc"), + (BetaAnalyticsDataAsyncClient, "grpc_asyncio"), + (BetaAnalyticsDataClient, "rest"), +]) +def test_beta_analytics_data_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 == ( + 'analyticsdata.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://analyticsdata.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.BetaAnalyticsDataGrpcTransport, "grpc"), + (transports.BetaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.BetaAnalyticsDataRestTransport, "rest"), +]) +def test_beta_analytics_data_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", [ + (BetaAnalyticsDataClient, "grpc"), + (BetaAnalyticsDataAsyncClient, "grpc_asyncio"), + (BetaAnalyticsDataClient, "rest"), +]) +def test_beta_analytics_data_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 == ( + 'analyticsdata.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://analyticsdata.googleapis.com' + ) + + +def test_beta_analytics_data_client_get_transport_class(): + transport = BetaAnalyticsDataClient.get_transport_class() + available_transports = [ + transports.BetaAnalyticsDataGrpcTransport, + transports.BetaAnalyticsDataRestTransport, + ] + assert transport in available_transports + + transport = BetaAnalyticsDataClient.get_transport_class("grpc") + assert transport == transports.BetaAnalyticsDataGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (BetaAnalyticsDataClient, transports.BetaAnalyticsDataGrpcTransport, "grpc"), + (BetaAnalyticsDataAsyncClient, transports.BetaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio"), + (BetaAnalyticsDataClient, transports.BetaAnalyticsDataRestTransport, "rest"), +]) +@mock.patch.object(BetaAnalyticsDataClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BetaAnalyticsDataClient)) +@mock.patch.object(BetaAnalyticsDataAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BetaAnalyticsDataAsyncClient)) +def test_beta_analytics_data_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(BetaAnalyticsDataClient, '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(BetaAnalyticsDataClient, '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, + 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): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # 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, + 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, + 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", [ + (BetaAnalyticsDataClient, transports.BetaAnalyticsDataGrpcTransport, "grpc", "true"), + (BetaAnalyticsDataAsyncClient, transports.BetaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (BetaAnalyticsDataClient, transports.BetaAnalyticsDataGrpcTransport, "grpc", "false"), + (BetaAnalyticsDataAsyncClient, transports.BetaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (BetaAnalyticsDataClient, transports.BetaAnalyticsDataRestTransport, "rest", "true"), + (BetaAnalyticsDataClient, transports.BetaAnalyticsDataRestTransport, "rest", "false"), +]) +@mock.patch.object(BetaAnalyticsDataClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BetaAnalyticsDataClient)) +@mock.patch.object(BetaAnalyticsDataAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BetaAnalyticsDataAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_beta_analytics_data_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 + 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 + 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, + 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", [ + BetaAnalyticsDataClient, BetaAnalyticsDataAsyncClient +]) +@mock.patch.object(BetaAnalyticsDataClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BetaAnalyticsDataClient)) +@mock.patch.object(BetaAnalyticsDataAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BetaAnalyticsDataAsyncClient)) +def test_beta_analytics_data_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 + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (BetaAnalyticsDataClient, transports.BetaAnalyticsDataGrpcTransport, "grpc"), + (BetaAnalyticsDataAsyncClient, transports.BetaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio"), + (BetaAnalyticsDataClient, transports.BetaAnalyticsDataRestTransport, "rest"), +]) +def test_beta_analytics_data_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, + 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", [ + (BetaAnalyticsDataClient, transports.BetaAnalyticsDataGrpcTransport, "grpc", grpc_helpers), + (BetaAnalyticsDataAsyncClient, transports.BetaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (BetaAnalyticsDataClient, transports.BetaAnalyticsDataRestTransport, "rest", None), +]) +def test_beta_analytics_data_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, + 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_beta_analytics_data_client_client_options_from_dict(): + with mock.patch('google.analytics.data_v1beta.services.beta_analytics_data.transports.BetaAnalyticsDataGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = BetaAnalyticsDataClient( + 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", [ + (BetaAnalyticsDataClient, transports.BetaAnalyticsDataGrpcTransport, "grpc", grpc_helpers), + (BetaAnalyticsDataAsyncClient, transports.BetaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_beta_analytics_data_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, + 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( + "analyticsdata.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/analytics', + 'https://www.googleapis.com/auth/analytics.readonly', +), + scopes=None, + default_host="analyticsdata.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_data_api.RunReportRequest, + dict, +]) +def test_run_report(request_type, transport: str = 'grpc'): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_data_api.RunReportResponse( + row_count=992, + kind='kind_value', + ) + response = client.run_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] == analytics_data_api.RunReportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.RunReportResponse) + assert response.row_count == 992 + assert response.kind == 'kind_value' + + +def test_run_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 = BetaAnalyticsDataClient( + credentials=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_report), + '__call__') as call: + client.run_report() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.RunReportRequest() + +@pytest.mark.asyncio +async def test_run_report_async(transport: str = 'grpc_asyncio', request_type=analytics_data_api.RunReportRequest): + client = BetaAnalyticsDataAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.RunReportResponse( + row_count=992, + kind='kind_value', + )) + response = await client.run_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.RunReportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.RunReportResponse) + assert response.row_count == 992 + assert response.kind == 'kind_value' + + +@pytest.mark.asyncio +async def test_run_report_async_from_dict(): + await test_run_report_async(request_type=dict) + + +def test_run_report_field_headers(): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_data_api.RunReportRequest() + + request.property = 'property_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_report), + '__call__') as call: + call.return_value = analytics_data_api.RunReportResponse() + client.run_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', + 'property=property_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_run_report_field_headers_async(): + client = BetaAnalyticsDataAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_data_api.RunReportRequest() + + request.property = 'property_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_report), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.RunReportResponse()) + await client.run_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', + 'property=property_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + analytics_data_api.RunPivotReportRequest, + dict, +]) +def test_run_pivot_report(request_type, transport: str = 'grpc'): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_pivot_report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_data_api.RunPivotReportResponse( + kind='kind_value', + ) + response = client.run_pivot_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] == analytics_data_api.RunPivotReportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.RunPivotReportResponse) + assert response.kind == 'kind_value' + + +def test_run_pivot_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 = BetaAnalyticsDataClient( + credentials=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_pivot_report), + '__call__') as call: + client.run_pivot_report() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.RunPivotReportRequest() + +@pytest.mark.asyncio +async def test_run_pivot_report_async(transport: str = 'grpc_asyncio', request_type=analytics_data_api.RunPivotReportRequest): + client = BetaAnalyticsDataAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_pivot_report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.RunPivotReportResponse( + kind='kind_value', + )) + response = await client.run_pivot_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.RunPivotReportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.RunPivotReportResponse) + assert response.kind == 'kind_value' + + +@pytest.mark.asyncio +async def test_run_pivot_report_async_from_dict(): + await test_run_pivot_report_async(request_type=dict) + + +def test_run_pivot_report_field_headers(): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_data_api.RunPivotReportRequest() + + request.property = 'property_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_pivot_report), + '__call__') as call: + call.return_value = analytics_data_api.RunPivotReportResponse() + client.run_pivot_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', + 'property=property_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_run_pivot_report_field_headers_async(): + client = BetaAnalyticsDataAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_data_api.RunPivotReportRequest() + + request.property = 'property_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_pivot_report), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.RunPivotReportResponse()) + await client.run_pivot_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', + 'property=property_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + analytics_data_api.BatchRunReportsRequest, + dict, +]) +def test_batch_run_reports(request_type, transport: str = 'grpc'): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_reports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_data_api.BatchRunReportsResponse( + kind='kind_value', + ) + response = client.batch_run_reports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.BatchRunReportsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.BatchRunReportsResponse) + assert response.kind == 'kind_value' + + +def test_batch_run_reports_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_reports), + '__call__') as call: + client.batch_run_reports() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.BatchRunReportsRequest() + +@pytest.mark.asyncio +async def test_batch_run_reports_async(transport: str = 'grpc_asyncio', request_type=analytics_data_api.BatchRunReportsRequest): + client = BetaAnalyticsDataAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_reports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.BatchRunReportsResponse( + kind='kind_value', + )) + response = await client.batch_run_reports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.BatchRunReportsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.BatchRunReportsResponse) + assert response.kind == 'kind_value' + + +@pytest.mark.asyncio +async def test_batch_run_reports_async_from_dict(): + await test_batch_run_reports_async(request_type=dict) + + +def test_batch_run_reports_field_headers(): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_data_api.BatchRunReportsRequest() + + request.property = 'property_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_reports), + '__call__') as call: + call.return_value = analytics_data_api.BatchRunReportsResponse() + client.batch_run_reports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_batch_run_reports_field_headers_async(): + client = BetaAnalyticsDataAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_data_api.BatchRunReportsRequest() + + request.property = 'property_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_reports), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.BatchRunReportsResponse()) + await client.batch_run_reports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_data_api.BatchRunPivotReportsRequest, + dict, +]) +def test_batch_run_pivot_reports(request_type, transport: str = 'grpc'): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_pivot_reports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_data_api.BatchRunPivotReportsResponse( + kind='kind_value', + ) + response = client.batch_run_pivot_reports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.BatchRunPivotReportsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.BatchRunPivotReportsResponse) + assert response.kind == 'kind_value' + + +def test_batch_run_pivot_reports_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_pivot_reports), + '__call__') as call: + client.batch_run_pivot_reports() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.BatchRunPivotReportsRequest() + +@pytest.mark.asyncio +async def test_batch_run_pivot_reports_async(transport: str = 'grpc_asyncio', request_type=analytics_data_api.BatchRunPivotReportsRequest): + client = BetaAnalyticsDataAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_pivot_reports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.BatchRunPivotReportsResponse( + kind='kind_value', + )) + response = await client.batch_run_pivot_reports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.BatchRunPivotReportsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.BatchRunPivotReportsResponse) + assert response.kind == 'kind_value' + + +@pytest.mark.asyncio +async def test_batch_run_pivot_reports_async_from_dict(): + await test_batch_run_pivot_reports_async(request_type=dict) + + +def test_batch_run_pivot_reports_field_headers(): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_data_api.BatchRunPivotReportsRequest() + + request.property = 'property_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_pivot_reports), + '__call__') as call: + call.return_value = analytics_data_api.BatchRunPivotReportsResponse() + client.batch_run_pivot_reports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_batch_run_pivot_reports_field_headers_async(): + client = BetaAnalyticsDataAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_data_api.BatchRunPivotReportsRequest() + + request.property = 'property_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_pivot_reports), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.BatchRunPivotReportsResponse()) + await client.batch_run_pivot_reports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_data_api.GetMetadataRequest, + dict, +]) +def test_get_metadata(request_type, transport: str = 'grpc'): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_data_api.Metadata( + name='name_value', + ) + response = client.get_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.GetMetadataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.Metadata) + assert response.name == 'name_value' + + +def test_get_metadata_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = BetaAnalyticsDataClient( + credentials=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_metadata), + '__call__') as call: + client.get_metadata() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.GetMetadataRequest() + +@pytest.mark.asyncio +async def test_get_metadata_async(transport: str = 'grpc_asyncio', request_type=analytics_data_api.GetMetadataRequest): + client = BetaAnalyticsDataAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.Metadata( + name='name_value', + )) + response = await client.get_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.GetMetadataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.Metadata) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_metadata_async_from_dict(): + await test_get_metadata_async(request_type=dict) + + +def test_get_metadata_field_headers(): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_data_api.GetMetadataRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata), + '__call__') as call: + call.return_value = analytics_data_api.Metadata() + client.get_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_metadata_field_headers_async(): + client = BetaAnalyticsDataAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_data_api.GetMetadataRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.Metadata()) + await client.get_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_metadata_flattened(): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_data_api.Metadata() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_metadata( + name='name_value', + ) + + # Establish that the 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_metadata_flattened_error(): + client = BetaAnalyticsDataClient( + credentials=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_metadata( + analytics_data_api.GetMetadataRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_metadata_flattened_async(): + client = BetaAnalyticsDataAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_data_api.Metadata() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.Metadata()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_metadata( + name='name_value', + ) + + # Establish that 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_metadata_flattened_error_async(): + client = BetaAnalyticsDataAsyncClient( + credentials=ga_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_metadata( + analytics_data_api.GetMetadataRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_data_api.RunRealtimeReportRequest, + dict, +]) +def test_run_realtime_report(request_type, transport: str = 'grpc'): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_realtime_report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_data_api.RunRealtimeReportResponse( + row_count=992, + kind='kind_value', + ) + response = client.run_realtime_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] == analytics_data_api.RunRealtimeReportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.RunRealtimeReportResponse) + assert response.row_count == 992 + assert response.kind == 'kind_value' + + +def test_run_realtime_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 = BetaAnalyticsDataClient( + credentials=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_realtime_report), + '__call__') as call: + client.run_realtime_report() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.RunRealtimeReportRequest() + +@pytest.mark.asyncio +async def test_run_realtime_report_async(transport: str = 'grpc_asyncio', request_type=analytics_data_api.RunRealtimeReportRequest): + client = BetaAnalyticsDataAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_realtime_report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.RunRealtimeReportResponse( + row_count=992, + kind='kind_value', + )) + response = await client.run_realtime_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.RunRealtimeReportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.RunRealtimeReportResponse) + assert response.row_count == 992 + assert response.kind == 'kind_value' + + +@pytest.mark.asyncio +async def test_run_realtime_report_async_from_dict(): + await test_run_realtime_report_async(request_type=dict) + + +def test_run_realtime_report_field_headers(): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_data_api.RunRealtimeReportRequest() + + request.property = 'property_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_realtime_report), + '__call__') as call: + call.return_value = analytics_data_api.RunRealtimeReportResponse() + client.run_realtime_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', + 'property=property_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_run_realtime_report_field_headers_async(): + client = BetaAnalyticsDataAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_data_api.RunRealtimeReportRequest() + + request.property = 'property_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_realtime_report), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.RunRealtimeReportResponse()) + await client.run_realtime_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', + 'property=property_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + analytics_data_api.CheckCompatibilityRequest, + dict, +]) +def test_check_compatibility(request_type, transport: str = 'grpc'): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_compatibility), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_data_api.CheckCompatibilityResponse( + ) + response = client.check_compatibility(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.CheckCompatibilityRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.CheckCompatibilityResponse) + + +def test_check_compatibility_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_compatibility), + '__call__') as call: + client.check_compatibility() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.CheckCompatibilityRequest() + +@pytest.mark.asyncio +async def test_check_compatibility_async(transport: str = 'grpc_asyncio', request_type=analytics_data_api.CheckCompatibilityRequest): + client = BetaAnalyticsDataAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_compatibility), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.CheckCompatibilityResponse( + )) + response = await client.check_compatibility(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_data_api.CheckCompatibilityRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.CheckCompatibilityResponse) + + +@pytest.mark.asyncio +async def test_check_compatibility_async_from_dict(): + await test_check_compatibility_async(request_type=dict) + + +def test_check_compatibility_field_headers(): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_data_api.CheckCompatibilityRequest() + + request.property = 'property_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_compatibility), + '__call__') as call: + call.return_value = analytics_data_api.CheckCompatibilityResponse() + client.check_compatibility(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_check_compatibility_field_headers_async(): + client = BetaAnalyticsDataAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_data_api.CheckCompatibilityRequest() + + request.property = 'property_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_compatibility), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.CheckCompatibilityResponse()) + await client.check_compatibility(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_data_api.RunReportRequest, + dict, +]) +def test_run_report_rest(request_type): + client = BetaAnalyticsDataClient( + 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_data_api.RunReportResponse( + row_count=992, + kind='kind_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = analytics_data_api.RunReportResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.run_report(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.RunReportResponse) + assert response.row_count == 992 + assert response.kind == 'kind_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_run_report_rest_interceptors(null_interceptor): + transport = transports.BetaAnalyticsDataRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BetaAnalyticsDataRestInterceptor(), + ) + client = BetaAnalyticsDataClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "post_run_report") as post, \ + mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "pre_run_report") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_data_api.RunReportRequest.pb(analytics_data_api.RunReportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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_data_api.RunReportResponse.to_json(analytics_data_api.RunReportResponse()) + + request = analytics_data_api.RunReportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_data_api.RunReportResponse() + + client.run_report(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_run_report_rest_bad_request(transport: str = 'rest', request_type=analytics_data_api.RunReportRequest): + client = BetaAnalyticsDataClient( + 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.run_report(request) + + +def test_run_report_rest_error(): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_data_api.RunPivotReportRequest, + dict, +]) +def test_run_pivot_report_rest(request_type): + client = BetaAnalyticsDataClient( + 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_data_api.RunPivotReportResponse( + kind='kind_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = analytics_data_api.RunPivotReportResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.run_pivot_report(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.RunPivotReportResponse) + assert response.kind == 'kind_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_run_pivot_report_rest_interceptors(null_interceptor): + transport = transports.BetaAnalyticsDataRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BetaAnalyticsDataRestInterceptor(), + ) + client = BetaAnalyticsDataClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "post_run_pivot_report") as post, \ + mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "pre_run_pivot_report") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_data_api.RunPivotReportRequest.pb(analytics_data_api.RunPivotReportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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_data_api.RunPivotReportResponse.to_json(analytics_data_api.RunPivotReportResponse()) + + request = analytics_data_api.RunPivotReportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_data_api.RunPivotReportResponse() + + client.run_pivot_report(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_run_pivot_report_rest_bad_request(transport: str = 'rest', request_type=analytics_data_api.RunPivotReportRequest): + client = BetaAnalyticsDataClient( + 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.run_pivot_report(request) + + +def test_run_pivot_report_rest_error(): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_data_api.BatchRunReportsRequest, + dict, +]) +def test_batch_run_reports_rest(request_type): + client = BetaAnalyticsDataClient( + 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_data_api.BatchRunReportsResponse( + kind='kind_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = analytics_data_api.BatchRunReportsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.batch_run_reports(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.BatchRunReportsResponse) + assert response.kind == 'kind_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_run_reports_rest_interceptors(null_interceptor): + transport = transports.BetaAnalyticsDataRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BetaAnalyticsDataRestInterceptor(), + ) + client = BetaAnalyticsDataClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "post_batch_run_reports") as post, \ + mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "pre_batch_run_reports") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_data_api.BatchRunReportsRequest.pb(analytics_data_api.BatchRunReportsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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_data_api.BatchRunReportsResponse.to_json(analytics_data_api.BatchRunReportsResponse()) + + request = analytics_data_api.BatchRunReportsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_data_api.BatchRunReportsResponse() + + client.batch_run_reports(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_run_reports_rest_bad_request(transport: str = 'rest', request_type=analytics_data_api.BatchRunReportsRequest): + client = BetaAnalyticsDataClient( + 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.batch_run_reports(request) + + +def test_batch_run_reports_rest_error(): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_data_api.BatchRunPivotReportsRequest, + dict, +]) +def test_batch_run_pivot_reports_rest(request_type): + client = BetaAnalyticsDataClient( + 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_data_api.BatchRunPivotReportsResponse( + kind='kind_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = analytics_data_api.BatchRunPivotReportsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.batch_run_pivot_reports(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.BatchRunPivotReportsResponse) + assert response.kind == 'kind_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_run_pivot_reports_rest_interceptors(null_interceptor): + transport = transports.BetaAnalyticsDataRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BetaAnalyticsDataRestInterceptor(), + ) + client = BetaAnalyticsDataClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "post_batch_run_pivot_reports") as post, \ + mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "pre_batch_run_pivot_reports") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_data_api.BatchRunPivotReportsRequest.pb(analytics_data_api.BatchRunPivotReportsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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_data_api.BatchRunPivotReportsResponse.to_json(analytics_data_api.BatchRunPivotReportsResponse()) + + request = analytics_data_api.BatchRunPivotReportsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_data_api.BatchRunPivotReportsResponse() + + client.batch_run_pivot_reports(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_run_pivot_reports_rest_bad_request(transport: str = 'rest', request_type=analytics_data_api.BatchRunPivotReportsRequest): + client = BetaAnalyticsDataClient( + 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.batch_run_pivot_reports(request) + + +def test_batch_run_pivot_reports_rest_error(): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_data_api.GetMetadataRequest, + dict, +]) +def test_get_metadata_rest(request_type): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/metadata'} + request = request_type(**request_init) + + # Mock the http request call within the method and 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_data_api.Metadata( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = analytics_data_api.Metadata.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_metadata(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.Metadata) + assert response.name == 'name_value' + + +def test_get_metadata_rest_required_fields(request_type=analytics_data_api.GetMetadataRequest): + transport_class = transports.BetaAnalyticsDataRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_metadata._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_metadata._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 = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_data_api.Metadata() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = analytics_data_api.Metadata.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_metadata(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_metadata_rest_unset_required_fields(): + transport = transports.BetaAnalyticsDataRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_metadata._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_metadata_rest_interceptors(null_interceptor): + transport = transports.BetaAnalyticsDataRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BetaAnalyticsDataRestInterceptor(), + ) + client = BetaAnalyticsDataClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "post_get_metadata") as post, \ + mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "pre_get_metadata") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_data_api.GetMetadataRequest.pb(analytics_data_api.GetMetadataRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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_data_api.Metadata.to_json(analytics_data_api.Metadata()) + + request = analytics_data_api.GetMetadataRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_data_api.Metadata() + + client.get_metadata(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_metadata_rest_bad_request(transport: str = 'rest', request_type=analytics_data_api.GetMetadataRequest): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/metadata'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_metadata(request) + + +def test_get_metadata_rest_flattened(): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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_data_api.Metadata() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/metadata'} + + # 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 + pb_return_value = analytics_data_api.Metadata.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_metadata(**mock_args) + + # Establish that the underlying call 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/*/metadata}" % client.transport._host, args[1]) + + +def test_get_metadata_rest_flattened_error(transport: str = 'rest'): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.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_metadata( + analytics_data_api.GetMetadataRequest(), + name='name_value', + ) + + +def test_get_metadata_rest_error(): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_data_api.RunRealtimeReportRequest, + dict, +]) +def test_run_realtime_report_rest(request_type): + client = BetaAnalyticsDataClient( + 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_data_api.RunRealtimeReportResponse( + row_count=992, + kind='kind_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = analytics_data_api.RunRealtimeReportResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.run_realtime_report(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.RunRealtimeReportResponse) + assert response.row_count == 992 + assert response.kind == 'kind_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_run_realtime_report_rest_interceptors(null_interceptor): + transport = transports.BetaAnalyticsDataRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BetaAnalyticsDataRestInterceptor(), + ) + client = BetaAnalyticsDataClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "post_run_realtime_report") as post, \ + mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "pre_run_realtime_report") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_data_api.RunRealtimeReportRequest.pb(analytics_data_api.RunRealtimeReportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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_data_api.RunRealtimeReportResponse.to_json(analytics_data_api.RunRealtimeReportResponse()) + + request = analytics_data_api.RunRealtimeReportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_data_api.RunRealtimeReportResponse() + + client.run_realtime_report(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_run_realtime_report_rest_bad_request(transport: str = 'rest', request_type=analytics_data_api.RunRealtimeReportRequest): + client = BetaAnalyticsDataClient( + 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.run_realtime_report(request) + + +def test_run_realtime_report_rest_error(): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_data_api.CheckCompatibilityRequest, + dict, +]) +def test_check_compatibility_rest(request_type): + client = BetaAnalyticsDataClient( + 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_data_api.CheckCompatibilityResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = analytics_data_api.CheckCompatibilityResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.check_compatibility(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.CheckCompatibilityResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_check_compatibility_rest_interceptors(null_interceptor): + transport = transports.BetaAnalyticsDataRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BetaAnalyticsDataRestInterceptor(), + ) + client = BetaAnalyticsDataClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "post_check_compatibility") as post, \ + mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "pre_check_compatibility") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_data_api.CheckCompatibilityRequest.pb(analytics_data_api.CheckCompatibilityRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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_data_api.CheckCompatibilityResponse.to_json(analytics_data_api.CheckCompatibilityResponse()) + + request = analytics_data_api.CheckCompatibilityRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_data_api.CheckCompatibilityResponse() + + client.check_compatibility(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_check_compatibility_rest_bad_request(transport: str = 'rest', request_type=analytics_data_api.CheckCompatibilityRequest): + client = BetaAnalyticsDataClient( + 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.check_compatibility(request) + + +def test_check_compatibility_rest_error(): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.BetaAnalyticsDataGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.BetaAnalyticsDataGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BetaAnalyticsDataClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.BetaAnalyticsDataGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BetaAnalyticsDataClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BetaAnalyticsDataClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.BetaAnalyticsDataGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BetaAnalyticsDataClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.BetaAnalyticsDataGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = BetaAnalyticsDataClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.BetaAnalyticsDataGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.BetaAnalyticsDataGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.BetaAnalyticsDataGrpcTransport, + transports.BetaAnalyticsDataGrpcAsyncIOTransport, + transports.BetaAnalyticsDataRestTransport, +]) +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 = BetaAnalyticsDataClient.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 = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.BetaAnalyticsDataGrpcTransport, + ) + +def test_beta_analytics_data_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.BetaAnalyticsDataTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_beta_analytics_data_base_transport(): + # Instantiate the base transport. + with mock.patch('google.analytics.data_v1beta.services.beta_analytics_data.transports.BetaAnalyticsDataTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.BetaAnalyticsDataTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'run_report', + 'run_pivot_report', + 'batch_run_reports', + 'batch_run_pivot_reports', + 'get_metadata', + 'run_realtime_report', + 'check_compatibility', + ) + 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_beta_analytics_data_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.data_v1beta.services.beta_analytics_data.transports.BetaAnalyticsDataTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BetaAnalyticsDataTransport( + 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', + 'https://www.googleapis.com/auth/analytics.readonly', +), + quota_project_id="octopus", + ) + + +def test_beta_analytics_data_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.data_v1beta.services.beta_analytics_data.transports.BetaAnalyticsDataTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BetaAnalyticsDataTransport() + adc.assert_called_once() + + +def test_beta_analytics_data_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) + BetaAnalyticsDataClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/analytics', + 'https://www.googleapis.com/auth/analytics.readonly', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BetaAnalyticsDataGrpcTransport, + transports.BetaAnalyticsDataGrpcAsyncIOTransport, + ], +) +def test_beta_analytics_data_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', 'https://www.googleapis.com/auth/analytics.readonly',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BetaAnalyticsDataGrpcTransport, + transports.BetaAnalyticsDataGrpcAsyncIOTransport, + transports.BetaAnalyticsDataRestTransport, + ], +) +def test_beta_analytics_data_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.BetaAnalyticsDataGrpcTransport, grpc_helpers), + (transports.BetaAnalyticsDataGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_beta_analytics_data_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( + "analyticsdata.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/analytics', + 'https://www.googleapis.com/auth/analytics.readonly', +), + scopes=["1", "2"], + default_host="analyticsdata.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.BetaAnalyticsDataGrpcTransport, transports.BetaAnalyticsDataGrpcAsyncIOTransport]) +def test_beta_analytics_data_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_beta_analytics_data_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.BetaAnalyticsDataRestTransport ( + 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_beta_analytics_data_host_no_port(transport_name): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='analyticsdata.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'analyticsdata.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://analyticsdata.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_beta_analytics_data_host_with_port(transport_name): + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='analyticsdata.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'analyticsdata.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://analyticsdata.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_beta_analytics_data_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = BetaAnalyticsDataClient( + credentials=creds1, + transport=transport_name, + ) + client2 = BetaAnalyticsDataClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.run_report._session + session2 = client2.transport.run_report._session + assert session1 != session2 + session1 = client1.transport.run_pivot_report._session + session2 = client2.transport.run_pivot_report._session + assert session1 != session2 + session1 = client1.transport.batch_run_reports._session + session2 = client2.transport.batch_run_reports._session + assert session1 != session2 + session1 = client1.transport.batch_run_pivot_reports._session + session2 = client2.transport.batch_run_pivot_reports._session + assert session1 != session2 + session1 = client1.transport.get_metadata._session + session2 = client2.transport.get_metadata._session + assert session1 != session2 + session1 = client1.transport.run_realtime_report._session + session2 = client2.transport.run_realtime_report._session + assert session1 != session2 + session1 = client1.transport.check_compatibility._session + session2 = client2.transport.check_compatibility._session + assert session1 != session2 +def test_beta_analytics_data_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.BetaAnalyticsDataGrpcTransport( + 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_beta_analytics_data_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.BetaAnalyticsDataGrpcAsyncIOTransport( + 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.BetaAnalyticsDataGrpcTransport, transports.BetaAnalyticsDataGrpcAsyncIOTransport]) +def test_beta_analytics_data_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.BetaAnalyticsDataGrpcTransport, transports.BetaAnalyticsDataGrpcAsyncIOTransport]) +def test_beta_analytics_data_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_metadata_path(): + property = "squid" + expected = "properties/{property}/metadata".format(property=property, ) + actual = BetaAnalyticsDataClient.metadata_path(property) + assert expected == actual + + +def test_parse_metadata_path(): + expected = { + "property": "clam", + } + path = BetaAnalyticsDataClient.metadata_path(**expected) + + # Check that the path construction is reversible. + actual = BetaAnalyticsDataClient.parse_metadata_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = BetaAnalyticsDataClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = BetaAnalyticsDataClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = BetaAnalyticsDataClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = BetaAnalyticsDataClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = BetaAnalyticsDataClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = BetaAnalyticsDataClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = BetaAnalyticsDataClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = BetaAnalyticsDataClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = BetaAnalyticsDataClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = BetaAnalyticsDataClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = BetaAnalyticsDataClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = BetaAnalyticsDataClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = BetaAnalyticsDataClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = BetaAnalyticsDataClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = BetaAnalyticsDataClient.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.BetaAnalyticsDataTransport, '_prep_wrapped_messages') as prep: + client = BetaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.BetaAnalyticsDataTransport, '_prep_wrapped_messages') as prep: + transport_class = BetaAnalyticsDataClient.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 = BetaAnalyticsDataAsyncClient( + 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 = BetaAnalyticsDataClient( + 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 = BetaAnalyticsDataClient( + 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", [ + (BetaAnalyticsDataClient, transports.BetaAnalyticsDataGrpcTransport), + (BetaAnalyticsDataAsyncClient, transports.BetaAnalyticsDataGrpcAsyncIOTransport), +]) +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, + 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, + ) From eec9ba38709a1f4c93a5d4564c23ab3a622537b6 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 9 Nov 2022 23:55:45 +0000 Subject: [PATCH 2/5] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../alpha_analytics_data/async_client.py | 24 +- .../services/alpha_analytics_data/client.py | 23 +- .../alpha_analytics_data/transports/base.py | 2 +- .../alpha_analytics_data/transports/grpc.py | 20 +- .../transports/grpc_asyncio.py | 16 +- .../alpha_analytics_data/transports/rest.py | 10 +- .../data_v1alpha/types/analytics_data_api.py | 34 +- google/analytics/data_v1alpha/types/data.py | 356 +- .../beta_analytics_data/async_client.py | 68 +- .../services/beta_analytics_data/client.py | 55 +- .../beta_analytics_data/transports/base.py | 2 +- .../beta_analytics_data/transports/grpc.py | 20 +- .../transports/grpc_asyncio.py | 16 +- .../beta_analytics_data/transports/rest.py | 22 +- .../data_v1beta/types/analytics_data_api.py | 252 +- google/analytics/data_v1beta/types/data.py | 264 +- owl-bot-staging/v1alpha/.coveragerc | 17 - owl-bot-staging/v1alpha/.flake8 | 33 - owl-bot-staging/v1alpha/MANIFEST.in | 2 - owl-bot-staging/v1alpha/README.rst | 49 - owl-bot-staging/v1alpha/docs/conf.py | 376 -- .../data_v1alpha/alpha_analytics_data.rst | 6 - .../v1alpha/docs/data_v1alpha/services.rst | 6 - .../v1alpha/docs/data_v1alpha/types.rst | 7 - owl-bot-staging/v1alpha/docs/index.rst | 7 - .../v1alpha/google/analytics/data/__init__.py | 157 - .../google/analytics/data/gapic_version.py | 16 - .../v1alpha/google/analytics/data/py.typed | 2 - .../google/analytics/data_v1alpha/__init__.py | 158 - .../data_v1alpha/gapic_metadata.json | 43 - .../google/analytics/data_v1alpha/py.typed | 2 - .../data_v1alpha/services/__init__.py | 15 - .../services/alpha_analytics_data/__init__.py | 22 - .../alpha_analytics_data/async_client.py | 294 -- .../services/alpha_analytics_data/client.py | 492 --- .../transports/__init__.py | 38 - .../alpha_analytics_data/transports/base.py | 155 - .../alpha_analytics_data/transports/grpc.py | 275 -- .../transports/grpc_asyncio.py | 274 -- .../alpha_analytics_data/transports/rest.py | 297 -- .../analytics/data_v1alpha/types/__init__.py | 152 - .../data_v1alpha/types/analytics_data_api.py | 220 -- .../analytics/data_v1alpha/types/data.py | 2404 ------------ owl-bot-staging/v1alpha/mypy.ini | 3 - owl-bot-staging/v1alpha/noxfile.py | 179 - ..._analytics_data_run_funnel_report_async.py | 51 - ...a_analytics_data_run_funnel_report_sync.py | 51 - .../scripts/fixup_data_v1alpha_keywords.py | 176 - owl-bot-staging/v1alpha/setup.py | 90 - .../v1alpha/testing/constraints-3.10.txt | 6 - .../v1alpha/testing/constraints-3.11.txt | 6 - .../v1alpha/testing/constraints-3.7.txt | 11 - .../v1alpha/testing/constraints-3.8.txt | 6 - .../v1alpha/testing/constraints-3.9.txt | 6 - owl-bot-staging/v1alpha/tests/__init__.py | 16 - .../v1alpha/tests/unit/__init__.py | 16 - .../v1alpha/tests/unit/gapic/__init__.py | 16 - .../tests/unit/gapic/data_v1alpha/__init__.py | 16 - .../data_v1alpha/test_alpha_analytics_data.py | 1455 -------- owl-bot-staging/v1beta/.coveragerc | 17 - owl-bot-staging/v1beta/.flake8 | 33 - owl-bot-staging/v1beta/MANIFEST.in | 2 - owl-bot-staging/v1beta/README.rst | 49 - owl-bot-staging/v1beta/docs/conf.py | 376 -- .../docs/data_v1beta/beta_analytics_data.rst | 6 - .../v1beta/docs/data_v1beta/services.rst | 6 - .../v1beta/docs/data_v1beta/types.rst | 7 - owl-bot-staging/v1beta/docs/index.rst | 7 - .../v1beta/google/analytics/data/__init__.py | 121 - .../google/analytics/data/gapic_version.py | 16 - .../v1beta/google/analytics/data/py.typed | 2 - .../google/analytics/data_v1beta/__init__.py | 122 - .../analytics/data_v1beta/gapic_metadata.json | 133 - .../google/analytics/data_v1beta/py.typed | 2 - .../data_v1beta/services/__init__.py | 15 - .../services/beta_analytics_data/__init__.py | 22 - .../beta_analytics_data/async_client.py | 846 ----- .../services/beta_analytics_data/client.py | 1058 ------ .../transports/__init__.py | 38 - .../beta_analytics_data/transports/base.py | 239 -- .../beta_analytics_data/transports/grpc.py | 467 --- .../transports/grpc_asyncio.py | 466 --- .../beta_analytics_data/transports/rest.py | 970 ----- .../analytics/data_v1beta/types/__init__.py | 116 - .../data_v1beta/types/analytics_data_api.py | 978 ----- .../analytics/data_v1beta/types/data.py | 1693 --------- owl-bot-staging/v1beta/mypy.ini | 3 - owl-bot-staging/v1beta/noxfile.py | 179 - ...tics_data_batch_run_pivot_reports_async.py | 51 - ...ytics_data_batch_run_pivot_reports_sync.py | 51 - ..._analytics_data_batch_run_reports_async.py | 51 - ...a_analytics_data_batch_run_reports_sync.py | 51 - ...nalytics_data_check_compatibility_async.py | 51 - ...analytics_data_check_compatibility_sync.py | 51 - ..._beta_analytics_data_get_metadata_async.py | 52 - ...d_beta_analytics_data_get_metadata_sync.py | 52 - ...a_analytics_data_run_pivot_report_async.py | 51 - ...ta_analytics_data_run_pivot_report_sync.py | 51 - ...nalytics_data_run_realtime_report_async.py | 51 - ...analytics_data_run_realtime_report_sync.py | 51 - ...ed_beta_analytics_data_run_report_async.py | 51 - ...ted_beta_analytics_data_run_report_sync.py | 51 - .../scripts/fixup_data_v1beta_keywords.py | 182 - owl-bot-staging/v1beta/setup.py | 90 - .../v1beta/testing/constraints-3.10.txt | 6 - .../v1beta/testing/constraints-3.11.txt | 6 - .../v1beta/testing/constraints-3.7.txt | 11 - .../v1beta/testing/constraints-3.8.txt | 6 - .../v1beta/testing/constraints-3.9.txt | 6 - owl-bot-staging/v1beta/tests/__init__.py | 16 - owl-bot-staging/v1beta/tests/unit/__init__.py | 16 - .../v1beta/tests/unit/gapic/__init__.py | 16 - .../tests/unit/gapic/data_v1beta/__init__.py | 16 - .../data_v1beta/test_beta_analytics_data.py | 3230 ----------------- .../snippet_metadata_data_v1alpha.json | 167 - .../snippet_metadata_data_v1beta.json | 1093 ------ ...etadata_google.analytics.data.v1alpha.json | 0 ...metadata_google.analytics.data.v1beta.json | 0 setup.py | 2 +- 119 files changed, 641 insertions(+), 21734 deletions(-) delete mode 100644 owl-bot-staging/v1alpha/.coveragerc delete mode 100644 owl-bot-staging/v1alpha/.flake8 delete mode 100644 owl-bot-staging/v1alpha/MANIFEST.in delete mode 100644 owl-bot-staging/v1alpha/README.rst delete mode 100644 owl-bot-staging/v1alpha/docs/conf.py delete mode 100644 owl-bot-staging/v1alpha/docs/data_v1alpha/alpha_analytics_data.rst delete mode 100644 owl-bot-staging/v1alpha/docs/data_v1alpha/services.rst delete mode 100644 owl-bot-staging/v1alpha/docs/data_v1alpha/types.rst delete mode 100644 owl-bot-staging/v1alpha/docs/index.rst delete mode 100644 owl-bot-staging/v1alpha/google/analytics/data/__init__.py delete mode 100644 owl-bot-staging/v1alpha/google/analytics/data/gapic_version.py delete mode 100644 owl-bot-staging/v1alpha/google/analytics/data/py.typed delete mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/__init__.py delete mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/gapic_metadata.json delete mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/py.typed delete mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/__init__.py delete mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/__init__.py delete mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/async_client.py delete mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py delete mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/__init__.py delete mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/base.py delete mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc.py delete mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest.py delete mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/__init__.py delete mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/analytics_data_api.py delete mode 100644 owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/data.py delete mode 100644 owl-bot-staging/v1alpha/mypy.ini delete mode 100644 owl-bot-staging/v1alpha/noxfile.py delete mode 100644 owl-bot-staging/v1alpha/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_async.py delete mode 100644 owl-bot-staging/v1alpha/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_sync.py delete mode 100644 owl-bot-staging/v1alpha/scripts/fixup_data_v1alpha_keywords.py delete mode 100644 owl-bot-staging/v1alpha/setup.py delete mode 100644 owl-bot-staging/v1alpha/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/v1alpha/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/v1alpha/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/v1alpha/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/v1alpha/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/v1alpha/tests/__init__.py delete mode 100644 owl-bot-staging/v1alpha/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1alpha/tests/unit/gapic/data_v1alpha/__init__.py delete mode 100644 owl-bot-staging/v1alpha/tests/unit/gapic/data_v1alpha/test_alpha_analytics_data.py delete mode 100644 owl-bot-staging/v1beta/.coveragerc delete mode 100644 owl-bot-staging/v1beta/.flake8 delete mode 100644 owl-bot-staging/v1beta/MANIFEST.in delete mode 100644 owl-bot-staging/v1beta/README.rst delete mode 100644 owl-bot-staging/v1beta/docs/conf.py delete mode 100644 owl-bot-staging/v1beta/docs/data_v1beta/beta_analytics_data.rst delete mode 100644 owl-bot-staging/v1beta/docs/data_v1beta/services.rst delete mode 100644 owl-bot-staging/v1beta/docs/data_v1beta/types.rst delete mode 100644 owl-bot-staging/v1beta/docs/index.rst delete mode 100644 owl-bot-staging/v1beta/google/analytics/data/__init__.py delete mode 100644 owl-bot-staging/v1beta/google/analytics/data/gapic_version.py delete mode 100644 owl-bot-staging/v1beta/google/analytics/data/py.typed delete mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/__init__.py delete mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/py.typed delete mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/services/__init__.py delete mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/__init__.py delete mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/async_client.py delete mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/client.py delete mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/__init__.py delete mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/base.py delete mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc.py delete mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/rest.py delete mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/types/__init__.py delete mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/types/analytics_data_api.py delete mode 100644 owl-bot-staging/v1beta/google/analytics/data_v1beta/types/data.py delete mode 100644 owl-bot-staging/v1beta/mypy.ini delete mode 100644 owl-bot-staging/v1beta/noxfile.py delete mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_async.py delete mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_sync.py delete mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_async.py delete mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_sync.py delete mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_async.py delete mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_sync.py delete mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_async.py delete mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_sync.py delete mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_async.py delete mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_sync.py delete mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_async.py delete mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_sync.py delete mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_report_async.py delete mode 100644 owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_report_sync.py delete mode 100644 owl-bot-staging/v1beta/scripts/fixup_data_v1beta_keywords.py delete mode 100644 owl-bot-staging/v1beta/setup.py delete mode 100644 owl-bot-staging/v1beta/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/v1beta/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/v1beta/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/v1beta/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/v1beta/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/v1beta/tests/__init__.py delete mode 100644 owl-bot-staging/v1beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1beta/tests/unit/gapic/data_v1beta/__init__.py delete mode 100644 owl-bot-staging/v1beta/tests/unit/gapic/data_v1beta/test_beta_analytics_data.py delete mode 100644 samples/generated_samples/snippet_metadata_data_v1alpha.json delete mode 100644 samples/generated_samples/snippet_metadata_data_v1beta.json rename {owl-bot-staging/v1alpha/samples => samples}/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json (100%) rename {owl-bot-staging/v1beta/samples => samples}/generated_samples/snippet_metadata_google.analytics.data.v1beta.json (100%) diff --git a/google/analytics/data_v1alpha/services/alpha_analytics_data/async_client.py b/google/analytics/data_v1alpha/services/alpha_analytics_data/async_client.py index 03d9623..8c01ae3 100644 --- a/google/analytics/data_v1alpha/services/alpha_analytics_data/async_client.py +++ b/google/analytics/data_v1alpha/services/alpha_analytics_data/async_client.py @@ -16,7 +16,17 @@ from collections import OrderedDict import functools import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 @@ -157,9 +167,9 @@ def transport(self) -> AlphaAnalyticsDataTransport: def __init__( self, *, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, AlphaAnalyticsDataTransport] = "grpc_asyncio", - client_options: ClientOptions = None, + client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the alpha analytics data client. @@ -203,10 +213,12 @@ def __init__( async def run_funnel_report( self, - request: Union[analytics_data_api.RunFunnelReportRequest, dict] = None, + request: Optional[ + Union[analytics_data_api.RunFunnelReportRequest, dict] + ] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.RunFunnelReportResponse: r"""Returns a customized funnel report of your Google Analytics @@ -248,7 +260,7 @@ async def sample_run_funnel_report(): print(response) Args: - request (Union[google.analytics.data_v1alpha.types.RunFunnelReportRequest, dict]): + request (Optional[Union[google.analytics.data_v1alpha.types.RunFunnelReportRequest, dict]]): The request object. The request for a funnel report. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. diff --git a/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py b/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py index 662fd6f..c6923e0 100644 --- a/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py +++ b/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py @@ -16,7 +16,18 @@ from collections import OrderedDict import os import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union, cast +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions @@ -59,7 +70,7 @@ class AlphaAnalyticsDataClientMeta(type): def get_transport_class( cls, - label: str = None, + label: Optional[str] = None, ) -> Type[AlphaAnalyticsDataTransport]: """Returns an appropriate transport class. @@ -312,7 +323,7 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AlphaAnalyticsDataTransport, None] = None, + transport: Optional[Union[str, AlphaAnalyticsDataTransport]] = None, client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -413,10 +424,12 @@ def __init__( def run_funnel_report( self, - request: Union[analytics_data_api.RunFunnelReportRequest, dict] = None, + request: Optional[ + Union[analytics_data_api.RunFunnelReportRequest, dict] + ] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.RunFunnelReportResponse: r"""Returns a customized funnel report of your Google Analytics diff --git a/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/base.py b/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/base.py index 05872ae..9cdb624 100644 --- a/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/base.py +++ b/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/base.py @@ -51,7 +51,7 @@ def __init__( self, *, host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, diff --git a/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc.py b/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc.py index 0a0f397..665e570 100644 --- a/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc.py +++ b/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc.py @@ -46,14 +46,14 @@ def __init__( self, *, host: str = "analyticsdata.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, @@ -180,8 +180,8 @@ def __init__( def create_channel( cls, host: str = "analyticsdata.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, diff --git a/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py b/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py index 280ba58..ae23871 100644 --- a/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py +++ b/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py @@ -48,7 +48,7 @@ class AlphaAnalyticsDataGrpcAsyncIOTransport(AlphaAnalyticsDataTransport): def create_channel( cls, host: str = "analyticsdata.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -91,15 +91,15 @@ def __init__( self, *, host: str = "analyticsdata.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, diff --git a/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest.py b/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest.py index 896d23c..0c82701 100644 --- a/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest.py +++ b/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest.py @@ -127,10 +127,10 @@ def __init__( self, *, host: str = "analyticsdata.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + 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, @@ -212,7 +212,7 @@ def __call__( request: analytics_data_api.RunFunnelReportRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.RunFunnelReportResponse: r"""Call the run funnel report method over HTTP. diff --git a/google/analytics/data_v1alpha/types/analytics_data_api.py b/google/analytics/data_v1alpha/types/analytics_data_api.py index a7d5dbd..e92a8f5 100644 --- a/google/analytics/data_v1alpha/types/analytics_data_api.py +++ b/google/analytics/data_v1alpha/types/analytics_data_api.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore from google.analytics.data_v1alpha.types import data @@ -39,7 +41,7 @@ class RunFunnelReportRequest(proto.Message): unspecified or consistent with the batch-level property. Example: properties/1234 - date_ranges (Sequence[google.analytics.data_v1alpha.types.DateRange]): + date_ranges (MutableSequence[google.analytics.data_v1alpha.types.DateRange]): Date ranges of data to read. If multiple date ranges are requested, each response row will contain a zero based date range index. If two @@ -70,7 +72,7 @@ class RunFunnelReportRequest(proto.Message): The funnel visualization type controls the dimensions present in the funnel visualization sub report response. If not specified, ``STANDARD_FUNNEL`` is used. - segments (Sequence[google.analytics.data_v1alpha.types.Segment]): + segments (MutableSequence[google.analytics.data_v1alpha.types.Segment]): The configurations of segments. Segments are subsets of a property's data. In a funnel report with segments, the funnel is evaluated in each @@ -110,50 +112,50 @@ class FunnelVisualizationType(proto.Enum): STANDARD_FUNNEL = 1 TRENDED_FUNNEL = 2 - property = proto.Field( + property: str = proto.Field( proto.STRING, number=1, ) - date_ranges = proto.RepeatedField( + date_ranges: MutableSequence[data.DateRange] = proto.RepeatedField( proto.MESSAGE, number=2, message=data.DateRange, ) - funnel = proto.Field( + funnel: data.Funnel = proto.Field( proto.MESSAGE, number=3, message=data.Funnel, ) - funnel_breakdown = proto.Field( + funnel_breakdown: data.FunnelBreakdown = proto.Field( proto.MESSAGE, number=4, message=data.FunnelBreakdown, ) - funnel_next_action = proto.Field( + funnel_next_action: data.FunnelNextAction = proto.Field( proto.MESSAGE, number=5, message=data.FunnelNextAction, ) - funnel_visualization_type = proto.Field( + funnel_visualization_type: FunnelVisualizationType = proto.Field( proto.ENUM, number=6, enum=FunnelVisualizationType, ) - segments = proto.RepeatedField( + segments: MutableSequence[data.Segment] = proto.RepeatedField( proto.MESSAGE, number=7, message=data.Segment, ) - limit = proto.Field( + limit: int = proto.Field( proto.INT64, number=9, ) - dimension_filter = proto.Field( + dimension_filter: data.FilterExpression = proto.Field( proto.MESSAGE, number=10, message=data.FilterExpression, ) - return_property_quota = proto.Field( + return_property_quota: bool = proto.Field( proto.BOOL, number=12, ) @@ -194,22 +196,22 @@ class RunFunnelReportResponse(proto.Message): between response types in JSON. """ - funnel_table = proto.Field( + funnel_table: data.FunnelSubReport = proto.Field( proto.MESSAGE, number=1, message=data.FunnelSubReport, ) - funnel_visualization = proto.Field( + funnel_visualization: data.FunnelSubReport = proto.Field( proto.MESSAGE, number=2, message=data.FunnelSubReport, ) - property_quota = proto.Field( + property_quota: data.PropertyQuota = proto.Field( proto.MESSAGE, number=3, message=data.PropertyQuota, ) - kind = proto.Field( + kind: str = proto.Field( proto.STRING, number=4, ) diff --git a/google/analytics/data_v1alpha/types/data.py b/google/analytics/data_v1alpha/types/data.py index 698b784..c317e84 100644 --- a/google/analytics/data_v1alpha/types/data.py +++ b/google/analytics/data_v1alpha/types/data.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + from google.protobuf import duration_pb2 # type: ignore import proto # type: ignore @@ -181,15 +183,15 @@ class DateRange(proto.Message): in the request: ``date_range_0``, ``date_range_1``, etc. """ - start_date = proto.Field( + start_date: str = proto.Field( proto.STRING, number=1, ) - end_date = proto.Field( + end_date: str = proto.Field( proto.STRING, number=2, ) - name = proto.Field( + name: str = proto.Field( proto.STRING, number=3, ) @@ -224,11 +226,11 @@ class Dimension(proto.Message): ", ", city). """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - dimension_expression = proto.Field( + dimension_expression: "DimensionExpression" = proto.Field( proto.MESSAGE, number=2, message="DimensionExpression", @@ -277,7 +279,7 @@ class CaseExpression(proto.Message): to a name in dimensions field of the request. """ - dimension_name = proto.Field( + dimension_name: str = proto.Field( proto.STRING, number=1, ) @@ -286,7 +288,7 @@ class ConcatenateExpression(proto.Message): r"""Used to combine dimension values to a single dimension. Attributes: - dimension_names (Sequence[str]): + dimension_names (MutableSequence[str]): Names of dimensions. The names must refer back to names in the dimensions field of the request. @@ -301,28 +303,28 @@ class ConcatenateExpression(proto.Message): response will contain "US,FR,JP". """ - dimension_names = proto.RepeatedField( + dimension_names: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=1, ) - delimiter = proto.Field( + delimiter: str = proto.Field( proto.STRING, number=2, ) - lower_case = proto.Field( + lower_case: CaseExpression = proto.Field( proto.MESSAGE, number=4, oneof="one_expression", message=CaseExpression, ) - upper_case = proto.Field( + upper_case: CaseExpression = proto.Field( proto.MESSAGE, number=5, oneof="one_expression", message=CaseExpression, ) - concatenate = proto.Field( + concatenate: ConcatenateExpression = proto.Field( proto.MESSAGE, number=6, oneof="one_expression", @@ -364,25 +366,25 @@ class FilterExpression(proto.Message): This field is a member of `oneof`_ ``expr``. """ - and_group = proto.Field( + and_group: "FilterExpressionList" = proto.Field( proto.MESSAGE, number=1, oneof="expr", message="FilterExpressionList", ) - or_group = proto.Field( + or_group: "FilterExpressionList" = proto.Field( proto.MESSAGE, number=2, oneof="expr", message="FilterExpressionList", ) - not_expression = proto.Field( + not_expression: "FilterExpression" = proto.Field( proto.MESSAGE, number=3, oneof="expr", message="FilterExpression", ) - filter = proto.Field( + filter: "Filter" = proto.Field( proto.MESSAGE, number=4, oneof="expr", @@ -394,11 +396,11 @@ class FilterExpressionList(proto.Message): r"""A list of filter expressions. Attributes: - expressions (Sequence[google.analytics.data_v1alpha.types.FilterExpression]): + expressions (MutableSequence[google.analytics.data_v1alpha.types.FilterExpression]): A list of filter expressions. """ - expressions = proto.RepeatedField( + expressions: MutableSequence["FilterExpression"] = proto.RepeatedField( proto.MESSAGE, number=1, message="FilterExpression", @@ -437,29 +439,29 @@ class Filter(proto.Message): This field is a member of `oneof`_ ``one_filter``. """ - field_name = proto.Field( + field_name: str = proto.Field( proto.STRING, number=1, ) - string_filter = proto.Field( + string_filter: "StringFilter" = proto.Field( proto.MESSAGE, number=2, oneof="one_filter", message="StringFilter", ) - in_list_filter = proto.Field( + in_list_filter: "InListFilter" = proto.Field( proto.MESSAGE, number=3, oneof="one_filter", message="InListFilter", ) - numeric_filter = proto.Field( + numeric_filter: "NumericFilter" = proto.Field( proto.MESSAGE, number=4, oneof="one_filter", message="NumericFilter", ) - between_filter = proto.Field( + between_filter: "BetweenFilter" = proto.Field( proto.MESSAGE, number=5, oneof="one_filter", @@ -489,16 +491,16 @@ class MatchType(proto.Enum): FULL_REGEXP = 5 PARTIAL_REGEXP = 6 - match_type = proto.Field( + match_type: MatchType = proto.Field( proto.ENUM, number=1, enum=MatchType, ) - value = proto.Field( + value: str = proto.Field( proto.STRING, number=2, ) - case_sensitive = proto.Field( + case_sensitive: bool = proto.Field( proto.BOOL, number=3, ) @@ -508,18 +510,18 @@ class InListFilter(proto.Message): r"""The result needs to be in a list of string values. Attributes: - values (Sequence[str]): + values (MutableSequence[str]): The list of string values. Must be non-empty. case_sensitive (bool): If true, the string value is case sensitive. """ - values = proto.RepeatedField( + values: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=1, ) - case_sensitive = proto.Field( + case_sensitive: bool = proto.Field( proto.BOOL, number=2, ) @@ -544,12 +546,12 @@ class Operation(proto.Enum): GREATER_THAN = 4 GREATER_THAN_OR_EQUAL = 5 - operation = proto.Field( + operation: Operation = proto.Field( proto.ENUM, number=1, enum=Operation, ) - value = proto.Field( + value: "NumericValue" = proto.Field( proto.MESSAGE, number=2, message="NumericValue", @@ -567,12 +569,12 @@ class BetweenFilter(proto.Message): Ends with this number. """ - from_value = proto.Field( + from_value: "NumericValue" = proto.Field( proto.MESSAGE, number=1, message="NumericValue", ) - to_value = proto.Field( + to_value: "NumericValue" = proto.Field( proto.MESSAGE, number=2, message="NumericValue", @@ -600,12 +602,12 @@ class NumericValue(proto.Message): This field is a member of `oneof`_ ``one_value``. """ - int64_value = proto.Field( + int64_value: int = proto.Field( proto.INT64, number=1, oneof="one_value", ) - double_value = proto.Field( + double_value: float = proto.Field( proto.DOUBLE, number=2, oneof="one_value", @@ -624,7 +626,7 @@ class DimensionHeader(proto.Message): The dimension's name. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -644,11 +646,11 @@ class MetricHeader(proto.Message): The metric's data type. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - type_ = proto.Field( + type_: "MetricType" = proto.Field( proto.ENUM, number=2, enum="MetricType", @@ -694,20 +696,20 @@ class Row(proto.Message): ] Attributes: - dimension_values (Sequence[google.analytics.data_v1alpha.types.DimensionValue]): + dimension_values (MutableSequence[google.analytics.data_v1alpha.types.DimensionValue]): List of requested dimension values. In a PivotReport, dimension_values are only listed for dimensions included in a pivot. - metric_values (Sequence[google.analytics.data_v1alpha.types.MetricValue]): + metric_values (MutableSequence[google.analytics.data_v1alpha.types.MetricValue]): List of requested visible metric values. """ - dimension_values = proto.RepeatedField( + dimension_values: MutableSequence["DimensionValue"] = proto.RepeatedField( proto.MESSAGE, number=1, message="DimensionValue", ) - metric_values = proto.RepeatedField( + metric_values: MutableSequence["MetricValue"] = proto.RepeatedField( proto.MESSAGE, number=2, message="MetricValue", @@ -727,7 +729,7 @@ class DimensionValue(proto.Message): This field is a member of `oneof`_ ``one_value``. """ - value = proto.Field( + value: str = proto.Field( proto.STRING, number=1, oneof="one_value", @@ -746,7 +748,7 @@ class MetricValue(proto.Message): This field is a member of `oneof`_ ``one_value``. """ - value = proto.Field( + value: str = proto.Field( proto.STRING, number=4, oneof="one_value", @@ -790,27 +792,27 @@ class PropertyQuota(proto.Message): dimensions. """ - tokens_per_day = proto.Field( + tokens_per_day: "QuotaStatus" = proto.Field( proto.MESSAGE, number=1, message="QuotaStatus", ) - tokens_per_hour = proto.Field( + tokens_per_hour: "QuotaStatus" = proto.Field( proto.MESSAGE, number=2, message="QuotaStatus", ) - concurrent_requests = proto.Field( + concurrent_requests: "QuotaStatus" = proto.Field( proto.MESSAGE, number=3, message="QuotaStatus", ) - server_errors_per_project_per_hour = proto.Field( + server_errors_per_project_per_hour: "QuotaStatus" = proto.Field( proto.MESSAGE, number=4, message="QuotaStatus", ) - potentially_thresholded_requests_per_hour = proto.Field( + potentially_thresholded_requests_per_hour: "QuotaStatus" = proto.Field( proto.MESSAGE, number=5, message="QuotaStatus", @@ -827,11 +829,11 @@ class QuotaStatus(proto.Message): Quota remaining after this request. """ - consumed = proto.Field( + consumed: int = proto.Field( proto.INT32, number=1, ) - remaining = proto.Field( + remaining: int = proto.Field( proto.INT32, number=2, ) @@ -856,12 +858,12 @@ class FunnelBreakdown(proto.Message): This field is a member of `oneof`_ ``_limit``. """ - breakdown_dimension = proto.Field( + breakdown_dimension: "Dimension" = proto.Field( proto.MESSAGE, number=1, message="Dimension", ) - limit = proto.Field( + limit: int = proto.Field( proto.INT64, number=2, optional=True, @@ -897,12 +899,12 @@ class FunnelNextAction(proto.Message): This field is a member of `oneof`_ ``_limit``. """ - next_action_dimension = proto.Field( + next_action_dimension: "Dimension" = proto.Field( proto.MESSAGE, number=1, message="Dimension", ) - limit = proto.Field( + limit: int = proto.Field( proto.INT64, number=2, optional=True, @@ -925,15 +927,15 @@ class Funnel(proto.Message): in any step, and in a closed funnel, users must enter the funnel in the first step. Optional. If unspecified, a closed funnel is used. - steps (Sequence[google.analytics.data_v1alpha.types.FunnelStep]): + steps (MutableSequence[google.analytics.data_v1alpha.types.FunnelStep]): The sequential steps of this funnel. """ - is_open_funnel = proto.Field( + is_open_funnel: bool = proto.Field( proto.BOOL, number=1, ) - steps = proto.RepeatedField( + steps: MutableSequence["FunnelStep"] = proto.RepeatedField( proto.MESSAGE, number=2, message="FunnelStep", @@ -975,21 +977,21 @@ class FunnelStep(proto.Message): included in this step of the funnel journey. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - is_directly_followed_by = proto.Field( + is_directly_followed_by: bool = proto.Field( proto.BOOL, number=2, ) - within_duration_from_prior_step = proto.Field( + within_duration_from_prior_step: duration_pb2.Duration = proto.Field( proto.MESSAGE, number=3, optional=True, message=duration_pb2.Duration, ) - filter_expression = proto.Field( + filter_expression: "FunnelFilterExpression" = proto.Field( proto.MESSAGE, number=4, message="FunnelFilterExpression", @@ -1002,41 +1004,41 @@ class FunnelSubReport(proto.Message): funnel. Attributes: - dimension_headers (Sequence[google.analytics.data_v1alpha.types.DimensionHeader]): + dimension_headers (MutableSequence[google.analytics.data_v1alpha.types.DimensionHeader]): Describes dimension columns. Funnel reports always include the funnel step dimension in sub report responses. Additional dimensions like breakdowns, dates, and next actions may be present in the response if requested. - metric_headers (Sequence[google.analytics.data_v1alpha.types.MetricHeader]): + metric_headers (MutableSequence[google.analytics.data_v1alpha.types.MetricHeader]): Describes metric columns. Funnel reports always include active users in sub report responses. The funnel table includes additional metrics like completion rate, abandonments, and abandonments rate. - rows (Sequence[google.analytics.data_v1alpha.types.Row]): + rows (MutableSequence[google.analytics.data_v1alpha.types.Row]): Rows of dimension value combinations and metric values in the report. metadata (google.analytics.data_v1alpha.types.FunnelResponseMetadata): Metadata for the funnel report. """ - dimension_headers = proto.RepeatedField( + dimension_headers: MutableSequence["DimensionHeader"] = proto.RepeatedField( proto.MESSAGE, number=1, message="DimensionHeader", ) - metric_headers = proto.RepeatedField( + metric_headers: MutableSequence["MetricHeader"] = proto.RepeatedField( proto.MESSAGE, number=2, message="MetricHeader", ) - rows = proto.RepeatedField( + rows: MutableSequence["Row"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Row", ) - metadata = proto.Field( + metadata: "FunnelResponseMetadata" = proto.Field( proto.MESSAGE, number=4, message="FunnelResponseMetadata", @@ -1058,12 +1060,12 @@ class UserSegment(proto.Message): segment. Optional. """ - user_inclusion_criteria = proto.Field( + user_inclusion_criteria: "UserSegmentCriteria" = proto.Field( proto.MESSAGE, number=1, message="UserSegmentCriteria", ) - exclusion = proto.Field( + exclusion: "UserSegmentExclusion" = proto.Field( proto.MESSAGE, number=2, message="UserSegmentExclusion", @@ -1075,24 +1077,28 @@ class UserSegmentCriteria(proto.Message): conditions in the criteria. Attributes: - and_condition_groups (Sequence[google.analytics.data_v1alpha.types.UserSegmentConditionGroup]): + and_condition_groups (MutableSequence[google.analytics.data_v1alpha.types.UserSegmentConditionGroup]): A user matches this criteria if the user matches each of these ``andConditionGroups`` and each of the ``andSequenceGroups``. ``andConditionGroups`` may be empty if ``andSequenceGroups`` are specified. - and_sequence_groups (Sequence[google.analytics.data_v1alpha.types.UserSegmentSequenceGroup]): + and_sequence_groups (MutableSequence[google.analytics.data_v1alpha.types.UserSegmentSequenceGroup]): A user matches this criteria if the user matches each of these ``andSequenceGroups`` and each of the ``andConditionGroups``. ``andSequenceGroups`` may be empty if ``andConditionGroups`` are specified. """ - and_condition_groups = proto.RepeatedField( + and_condition_groups: MutableSequence[ + "UserSegmentConditionGroup" + ] = proto.RepeatedField( proto.MESSAGE, number=1, message="UserSegmentConditionGroup", ) - and_sequence_groups = proto.RepeatedField( + and_sequence_groups: MutableSequence[ + "UserSegmentSequenceGroup" + ] = proto.RepeatedField( proto.MESSAGE, number=2, message="UserSegmentSequenceGroup", @@ -1128,12 +1134,12 @@ class UserSegmentConditionGroup(proto.Message): metrics, and/or parameters. """ - condition_scoping = proto.Field( + condition_scoping: "UserCriteriaScoping" = proto.Field( proto.ENUM, number=1, enum="UserCriteriaScoping", ) - segment_filter_expression = proto.Field( + segment_filter_expression: "SegmentFilterExpression" = proto.Field( proto.MESSAGE, number=2, message="SegmentFilterExpression", @@ -1166,23 +1172,23 @@ class UserSegmentSequenceGroup(proto.Message): ``sequenceMaximumDuration`` is optional, and if unspecified, sequences can be completed in any time duration. - user_sequence_steps (Sequence[google.analytics.data_v1alpha.types.UserSequenceStep]): + user_sequence_steps (MutableSequence[google.analytics.data_v1alpha.types.UserSequenceStep]): An ordered sequence of condition steps. A user's events must complete each step in order for the user to match the ``UserSegmentSequenceGroup``. """ - sequence_scoping = proto.Field( + sequence_scoping: "UserCriteriaScoping" = proto.Field( proto.ENUM, number=1, enum="UserCriteriaScoping", ) - sequence_maximum_duration = proto.Field( + sequence_maximum_duration: duration_pb2.Duration = proto.Field( proto.MESSAGE, number=2, message=duration_pb2.Duration, ) - user_sequence_steps = proto.RepeatedField( + user_sequence_steps: MutableSequence["UserSequenceStep"] = proto.RepeatedField( proto.MESSAGE, number=3, message="UserSequenceStep", @@ -1218,16 +1224,16 @@ class UserSequenceStep(proto.Message): parameters. """ - is_directly_followed_by = proto.Field( + is_directly_followed_by: bool = proto.Field( proto.BOOL, number=1, ) - step_scoping = proto.Field( + step_scoping: "UserCriteriaScoping" = proto.Field( proto.ENUM, number=2, enum="UserCriteriaScoping", ) - segment_filter_expression = proto.Field( + segment_filter_expression: "SegmentFilterExpression" = proto.Field( proto.MESSAGE, number=3, message="SegmentFilterExpression", @@ -1249,12 +1255,12 @@ class UserSegmentExclusion(proto.Message): membership in the segment for the ``userExclusionDuration``. """ - user_exclusion_duration = proto.Field( + user_exclusion_duration: "UserExclusionDuration" = proto.Field( proto.ENUM, number=1, enum="UserExclusionDuration", ) - user_exclusion_criteria = proto.Field( + user_exclusion_criteria: "UserSegmentCriteria" = proto.Field( proto.MESSAGE, number=2, message="UserSegmentCriteria", @@ -1275,12 +1281,12 @@ class SessionSegment(proto.Message): segment. Optional. """ - session_inclusion_criteria = proto.Field( + session_inclusion_criteria: "SessionSegmentCriteria" = proto.Field( proto.MESSAGE, number=1, message="SessionSegmentCriteria", ) - exclusion = proto.Field( + exclusion: "SessionSegmentExclusion" = proto.Field( proto.MESSAGE, number=2, message="SessionSegmentExclusion", @@ -1292,12 +1298,14 @@ class SessionSegmentCriteria(proto.Message): conditions in the criteria. Attributes: - and_condition_groups (Sequence[google.analytics.data_v1alpha.types.SessionSegmentConditionGroup]): + and_condition_groups (MutableSequence[google.analytics.data_v1alpha.types.SessionSegmentConditionGroup]): A session matches this criteria if the session matches each of these ``andConditionGroups``. """ - and_condition_groups = proto.RepeatedField( + and_condition_groups: MutableSequence[ + "SessionSegmentConditionGroup" + ] = proto.RepeatedField( proto.MESSAGE, number=1, message="SessionSegmentConditionGroup", @@ -1333,12 +1341,12 @@ class SessionSegmentConditionGroup(proto.Message): metrics, and/or parameters. """ - condition_scoping = proto.Field( + condition_scoping: "SessionCriteriaScoping" = proto.Field( proto.ENUM, number=1, enum="SessionCriteriaScoping", ) - segment_filter_expression = proto.Field( + segment_filter_expression: "SegmentFilterExpression" = proto.Field( proto.MESSAGE, number=2, message="SegmentFilterExpression", @@ -1361,12 +1369,12 @@ class SessionSegmentExclusion(proto.Message): ``sessionExclusionDuration``. """ - session_exclusion_duration = proto.Field( + session_exclusion_duration: "SessionExclusionDuration" = proto.Field( proto.ENUM, number=1, enum="SessionExclusionDuration", ) - session_exclusion_criteria = proto.Field( + session_exclusion_criteria: "SessionSegmentCriteria" = proto.Field( proto.MESSAGE, number=2, message="SessionSegmentCriteria", @@ -1388,12 +1396,12 @@ class EventSegment(proto.Message): segment. Optional. """ - event_inclusion_criteria = proto.Field( + event_inclusion_criteria: "EventSegmentCriteria" = proto.Field( proto.MESSAGE, number=1, message="EventSegmentCriteria", ) - exclusion = proto.Field( + exclusion: "EventSegmentExclusion" = proto.Field( proto.MESSAGE, number=2, message="EventSegmentExclusion", @@ -1405,12 +1413,14 @@ class EventSegmentCriteria(proto.Message): in the criteria. Attributes: - and_condition_groups (Sequence[google.analytics.data_v1alpha.types.EventSegmentConditionGroup]): + and_condition_groups (MutableSequence[google.analytics.data_v1alpha.types.EventSegmentConditionGroup]): An event matches this criteria if the event matches each of these ``andConditionGroups``. """ - and_condition_groups = proto.RepeatedField( + and_condition_groups: MutableSequence[ + "EventSegmentConditionGroup" + ] = proto.RepeatedField( proto.MESSAGE, number=1, message="EventSegmentConditionGroup", @@ -1435,12 +1445,12 @@ class EventSegmentConditionGroup(proto.Message): metrics, and/or parameters. """ - condition_scoping = proto.Field( + condition_scoping: "EventCriteriaScoping" = proto.Field( proto.ENUM, number=1, enum="EventCriteriaScoping", ) - segment_filter_expression = proto.Field( + segment_filter_expression: "SegmentFilterExpression" = proto.Field( proto.MESSAGE, number=2, message="SegmentFilterExpression", @@ -1463,12 +1473,12 @@ class EventSegmentExclusion(proto.Message): ``eventExclusionDuration``. """ - event_exclusion_duration = proto.Field( + event_exclusion_duration: "EventExclusionDuration" = proto.Field( proto.ENUM, number=1, enum="EventExclusionDuration", ) - event_exclusion_criteria = proto.Field( + event_exclusion_criteria: "EventSegmentCriteria" = proto.Field( proto.MESSAGE, number=2, message="EventSegmentCriteria", @@ -1517,23 +1527,23 @@ class Segment(proto.Message): This field is a member of `oneof`_ ``one_segment_scope``. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - user_segment = proto.Field( + user_segment: "UserSegment" = proto.Field( proto.MESSAGE, number=2, oneof="one_segment_scope", message="UserSegment", ) - session_segment = proto.Field( + session_segment: "SessionSegment" = proto.Field( proto.MESSAGE, number=3, oneof="one_segment_scope", message="SessionSegment", ) - event_segment = proto.Field( + event_segment: "EventSegment" = proto.Field( proto.MESSAGE, number=4, oneof="one_segment_scope", @@ -1581,31 +1591,31 @@ class SegmentFilterExpression(proto.Message): This field is a member of `oneof`_ ``expr``. """ - and_group = proto.Field( + and_group: "SegmentFilterExpressionList" = proto.Field( proto.MESSAGE, number=1, oneof="expr", message="SegmentFilterExpressionList", ) - or_group = proto.Field( + or_group: "SegmentFilterExpressionList" = proto.Field( proto.MESSAGE, number=2, oneof="expr", message="SegmentFilterExpressionList", ) - not_expression = proto.Field( + not_expression: "SegmentFilterExpression" = proto.Field( proto.MESSAGE, number=3, oneof="expr", message="SegmentFilterExpression", ) - segment_filter = proto.Field( + segment_filter: "SegmentFilter" = proto.Field( proto.MESSAGE, number=4, oneof="expr", message="SegmentFilter", ) - segment_event_filter = proto.Field( + segment_event_filter: "SegmentEventFilter" = proto.Field( proto.MESSAGE, number=5, oneof="expr", @@ -1617,11 +1627,11 @@ class SegmentFilterExpressionList(proto.Message): r"""A list of segment filter expressions. Attributes: - expressions (Sequence[google.analytics.data_v1alpha.types.SegmentFilterExpression]): + expressions (MutableSequence[google.analytics.data_v1alpha.types.SegmentFilterExpression]): The list of segment filter expressions """ - expressions = proto.RepeatedField( + expressions: MutableSequence["SegmentFilterExpression"] = proto.RepeatedField( proto.MESSAGE, number=1, message="SegmentFilterExpression", @@ -1661,35 +1671,35 @@ class SegmentFilter(proto.Message): Specifies the scope for the filter. """ - field_name = proto.Field( + field_name: str = proto.Field( proto.STRING, number=1, ) - string_filter = proto.Field( + string_filter: "StringFilter" = proto.Field( proto.MESSAGE, number=4, oneof="one_filter", message="StringFilter", ) - in_list_filter = proto.Field( + in_list_filter: "InListFilter" = proto.Field( proto.MESSAGE, number=5, oneof="one_filter", message="InListFilter", ) - numeric_filter = proto.Field( + numeric_filter: "NumericFilter" = proto.Field( proto.MESSAGE, number=6, oneof="one_filter", message="NumericFilter", ) - between_filter = proto.Field( + between_filter: "BetweenFilter" = proto.Field( proto.MESSAGE, number=7, oneof="one_filter", message="BetweenFilter", ) - filter_scoping = proto.Field( + filter_scoping: "SegmentFilterScoping" = proto.Field( proto.MESSAGE, number=8, message="SegmentFilterScoping", @@ -1721,7 +1731,7 @@ class SegmentFilterScoping(proto.Message): This field is a member of `oneof`_ ``_at_any_point_in_time``. """ - at_any_point_in_time = proto.Field( + at_any_point_in_time: bool = proto.Field( proto.BOOL, number=1, optional=True, @@ -1750,16 +1760,18 @@ class SegmentEventFilter(proto.Message): This field is a member of `oneof`_ ``_segment_parameter_filter_expression``. """ - event_name = proto.Field( + event_name: str = proto.Field( proto.STRING, number=1, optional=True, ) - segment_parameter_filter_expression = proto.Field( - proto.MESSAGE, - number=2, - optional=True, - message="SegmentParameterFilterExpression", + segment_parameter_filter_expression: "SegmentParameterFilterExpression" = ( + proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message="SegmentParameterFilterExpression", + ) ) @@ -1795,25 +1807,25 @@ class SegmentParameterFilterExpression(proto.Message): This field is a member of `oneof`_ ``expr``. """ - and_group = proto.Field( + and_group: "SegmentParameterFilterExpressionList" = proto.Field( proto.MESSAGE, number=1, oneof="expr", message="SegmentParameterFilterExpressionList", ) - or_group = proto.Field( + or_group: "SegmentParameterFilterExpressionList" = proto.Field( proto.MESSAGE, number=2, oneof="expr", message="SegmentParameterFilterExpressionList", ) - not_expression = proto.Field( + not_expression: "SegmentParameterFilterExpression" = proto.Field( proto.MESSAGE, number=3, oneof="expr", message="SegmentParameterFilterExpression", ) - segment_parameter_filter = proto.Field( + segment_parameter_filter: "SegmentParameterFilter" = proto.Field( proto.MESSAGE, number=4, oneof="expr", @@ -1825,12 +1837,14 @@ class SegmentParameterFilterExpressionList(proto.Message): r"""A list of segment parameter filter expressions. Attributes: - expressions (Sequence[google.analytics.data_v1alpha.types.SegmentParameterFilterExpression]): + expressions (MutableSequence[google.analytics.data_v1alpha.types.SegmentParameterFilterExpression]): The list of segment parameter filter expressions. """ - expressions = proto.RepeatedField( + expressions: MutableSequence[ + "SegmentParameterFilterExpression" + ] = proto.RepeatedField( proto.MESSAGE, number=1, message="SegmentParameterFilterExpression", @@ -1898,41 +1912,41 @@ class SegmentParameterFilter(proto.Message): Specifies the scope for the filter. """ - event_parameter_name = proto.Field( + event_parameter_name: str = proto.Field( proto.STRING, number=1, oneof="one_parameter", ) - item_parameter_name = proto.Field( + item_parameter_name: str = proto.Field( proto.STRING, number=2, oneof="one_parameter", ) - string_filter = proto.Field( + string_filter: "StringFilter" = proto.Field( proto.MESSAGE, number=4, oneof="one_filter", message="StringFilter", ) - in_list_filter = proto.Field( + in_list_filter: "InListFilter" = proto.Field( proto.MESSAGE, number=5, oneof="one_filter", message="InListFilter", ) - numeric_filter = proto.Field( + numeric_filter: "NumericFilter" = proto.Field( proto.MESSAGE, number=6, oneof="one_filter", message="NumericFilter", ) - between_filter = proto.Field( + between_filter: "BetweenFilter" = proto.Field( proto.MESSAGE, number=7, oneof="one_filter", message="BetweenFilter", ) - filter_scoping = proto.Field( + filter_scoping: "SegmentParameterFilterScoping" = proto.Field( proto.MESSAGE, number=8, message="SegmentParameterFilterScoping", @@ -1979,7 +1993,7 @@ class SegmentParameterFilterScoping(proto.Message): This field is a member of `oneof`_ ``_in_any_n_day_period``. """ - in_any_n_day_period = proto.Field( + in_any_n_day_period: int = proto.Field( proto.INT64, number=1, optional=True, @@ -2026,31 +2040,31 @@ class FunnelFilterExpression(proto.Message): This field is a member of `oneof`_ ``expr``. """ - and_group = proto.Field( + and_group: "FunnelFilterExpressionList" = proto.Field( proto.MESSAGE, number=1, oneof="expr", message="FunnelFilterExpressionList", ) - or_group = proto.Field( + or_group: "FunnelFilterExpressionList" = proto.Field( proto.MESSAGE, number=2, oneof="expr", message="FunnelFilterExpressionList", ) - not_expression = proto.Field( + not_expression: "FunnelFilterExpression" = proto.Field( proto.MESSAGE, number=3, oneof="expr", message="FunnelFilterExpression", ) - funnel_field_filter = proto.Field( + funnel_field_filter: "FunnelFieldFilter" = proto.Field( proto.MESSAGE, number=4, oneof="expr", message="FunnelFieldFilter", ) - funnel_event_filter = proto.Field( + funnel_event_filter: "FunnelEventFilter" = proto.Field( proto.MESSAGE, number=5, oneof="expr", @@ -2062,11 +2076,11 @@ class FunnelFilterExpressionList(proto.Message): r"""A list of funnel filter expressions. Attributes: - expressions (Sequence[google.analytics.data_v1alpha.types.FunnelFilterExpression]): + expressions (MutableSequence[google.analytics.data_v1alpha.types.FunnelFilterExpression]): The list of funnel filter expressions. """ - expressions = proto.RepeatedField( + expressions: MutableSequence["FunnelFilterExpression"] = proto.RepeatedField( proto.MESSAGE, number=1, message="FunnelFilterExpression", @@ -2104,29 +2118,29 @@ class FunnelFieldFilter(proto.Message): This field is a member of `oneof`_ ``one_filter``. """ - field_name = proto.Field( + field_name: str = proto.Field( proto.STRING, number=1, ) - string_filter = proto.Field( + string_filter: "StringFilter" = proto.Field( proto.MESSAGE, number=4, oneof="one_filter", message="StringFilter", ) - in_list_filter = proto.Field( + in_list_filter: "InListFilter" = proto.Field( proto.MESSAGE, number=5, oneof="one_filter", message="InListFilter", ) - numeric_filter = proto.Field( + numeric_filter: "NumericFilter" = proto.Field( proto.MESSAGE, number=6, oneof="one_filter", message="NumericFilter", ) - between_filter = proto.Field( + between_filter: "BetweenFilter" = proto.Field( proto.MESSAGE, number=7, oneof="one_filter", @@ -2156,12 +2170,12 @@ class FunnelEventFilter(proto.Message): This field is a member of `oneof`_ ``_funnel_parameter_filter_expression``. """ - event_name = proto.Field( + event_name: str = proto.Field( proto.STRING, number=1, optional=True, ) - funnel_parameter_filter_expression = proto.Field( + funnel_parameter_filter_expression: "FunnelParameterFilterExpression" = proto.Field( proto.MESSAGE, number=2, optional=True, @@ -2201,25 +2215,25 @@ class FunnelParameterFilterExpression(proto.Message): This field is a member of `oneof`_ ``expr``. """ - and_group = proto.Field( + and_group: "FunnelParameterFilterExpressionList" = proto.Field( proto.MESSAGE, number=1, oneof="expr", message="FunnelParameterFilterExpressionList", ) - or_group = proto.Field( + or_group: "FunnelParameterFilterExpressionList" = proto.Field( proto.MESSAGE, number=2, oneof="expr", message="FunnelParameterFilterExpressionList", ) - not_expression = proto.Field( + not_expression: "FunnelParameterFilterExpression" = proto.Field( proto.MESSAGE, number=3, oneof="expr", message="FunnelParameterFilterExpression", ) - funnel_parameter_filter = proto.Field( + funnel_parameter_filter: "FunnelParameterFilter" = proto.Field( proto.MESSAGE, number=4, oneof="expr", @@ -2231,12 +2245,14 @@ class FunnelParameterFilterExpressionList(proto.Message): r"""A list of funnel parameter filter expressions. Attributes: - expressions (Sequence[google.analytics.data_v1alpha.types.FunnelParameterFilterExpression]): + expressions (MutableSequence[google.analytics.data_v1alpha.types.FunnelParameterFilterExpression]): The list of funnel parameter filter expressions. """ - expressions = proto.RepeatedField( + expressions: MutableSequence[ + "FunnelParameterFilterExpression" + ] = proto.RepeatedField( proto.MESSAGE, number=1, message="FunnelParameterFilterExpression", @@ -2302,35 +2318,35 @@ class FunnelParameterFilter(proto.Message): This field is a member of `oneof`_ ``one_filter``. """ - event_parameter_name = proto.Field( + event_parameter_name: str = proto.Field( proto.STRING, number=1, oneof="one_parameter", ) - item_parameter_name = proto.Field( + item_parameter_name: str = proto.Field( proto.STRING, number=2, oneof="one_parameter", ) - string_filter = proto.Field( + string_filter: "StringFilter" = proto.Field( proto.MESSAGE, number=4, oneof="one_filter", message="StringFilter", ) - in_list_filter = proto.Field( + in_list_filter: "InListFilter" = proto.Field( proto.MESSAGE, number=5, oneof="one_filter", message="InListFilter", ) - numeric_filter = proto.Field( + numeric_filter: "NumericFilter" = proto.Field( proto.MESSAGE, number=6, oneof="one_filter", message="NumericFilter", ) - between_filter = proto.Field( + between_filter: "BetweenFilter" = proto.Field( proto.MESSAGE, number=7, oneof="one_filter", @@ -2343,7 +2359,7 @@ class FunnelResponseMetadata(proto.Message): information about the funnel report. Attributes: - sampling_metadatas (Sequence[google.analytics.data_v1alpha.types.SamplingMetadata]): + sampling_metadatas (MutableSequence[google.analytics.data_v1alpha.types.SamplingMetadata]): If funnel report results are `sampled `__, this describes what percentage of events were used in this @@ -2356,7 +2372,7 @@ class FunnelResponseMetadata(proto.Message): be defined. """ - sampling_metadatas = proto.RepeatedField( + sampling_metadatas: MutableSequence["SamplingMetadata"] = proto.RepeatedField( proto.MESSAGE, number=1, message="SamplingMetadata", @@ -2389,11 +2405,11 @@ class SamplingMetadata(proto.Message): ``samplesReadCount/samplingSpaceSize``. """ - samples_read_count = proto.Field( + samples_read_count: int = proto.Field( proto.INT64, number=1, ) - sampling_space_size = proto.Field( + sampling_space_size: int = proto.Field( proto.INT64, number=2, ) diff --git a/google/analytics/data_v1beta/services/beta_analytics_data/async_client.py b/google/analytics/data_v1beta/services/beta_analytics_data/async_client.py index 60b60dd..704df48 100644 --- a/google/analytics/data_v1beta/services/beta_analytics_data/async_client.py +++ b/google/analytics/data_v1beta/services/beta_analytics_data/async_client.py @@ -16,7 +16,17 @@ from collections import OrderedDict import functools import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 @@ -158,9 +168,9 @@ def transport(self) -> BetaAnalyticsDataTransport: def __init__( self, *, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, BetaAnalyticsDataTransport] = "grpc_asyncio", - client_options: ClientOptions = None, + client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the beta analytics data client. @@ -204,10 +214,10 @@ def __init__( async def run_report( self, - request: Union[analytics_data_api.RunReportRequest, dict] = None, + request: Optional[Union[analytics_data_api.RunReportRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.RunReportResponse: r"""Returns a customized report of your Google Analytics event data. @@ -249,7 +259,7 @@ async def sample_run_report(): print(response) Args: - request (Union[google.analytics.data_v1beta.types.RunReportRequest, dict]): + request (Optional[Union[google.analytics.data_v1beta.types.RunReportRequest, dict]]): The request object. The request to generate a report. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -293,10 +303,10 @@ async def sample_run_report(): async def run_pivot_report( self, - request: Union[analytics_data_api.RunPivotReportRequest, dict] = None, + request: Optional[Union[analytics_data_api.RunPivotReportRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.RunPivotReportResponse: r"""Returns a customized pivot report of your Google @@ -332,7 +342,7 @@ async def sample_run_pivot_report(): print(response) Args: - request (Union[google.analytics.data_v1beta.types.RunPivotReportRequest, dict]): + request (Optional[Union[google.analytics.data_v1beta.types.RunPivotReportRequest, dict]]): The request object. The request to generate a pivot report. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -377,10 +387,12 @@ async def sample_run_pivot_report(): async def batch_run_reports( self, - request: Union[analytics_data_api.BatchRunReportsRequest, dict] = None, + request: Optional[ + Union[analytics_data_api.BatchRunReportsRequest, dict] + ] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.BatchRunReportsResponse: r"""Returns multiple reports in a batch. All reports must @@ -412,7 +424,7 @@ async def sample_batch_run_reports(): print(response) Args: - request (Union[google.analytics.data_v1beta.types.BatchRunReportsRequest, dict]): + request (Optional[Union[google.analytics.data_v1beta.types.BatchRunReportsRequest, dict]]): The request object. The batch request containing multiple report requests. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -457,10 +469,12 @@ async def sample_batch_run_reports(): async def batch_run_pivot_reports( self, - request: Union[analytics_data_api.BatchRunPivotReportsRequest, dict] = None, + request: Optional[ + Union[analytics_data_api.BatchRunPivotReportsRequest, dict] + ] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.BatchRunPivotReportsResponse: r"""Returns multiple pivot reports in a batch. All @@ -492,7 +506,7 @@ async def sample_batch_run_pivot_reports(): print(response) Args: - request (Union[google.analytics.data_v1beta.types.BatchRunPivotReportsRequest, dict]): + request (Optional[Union[google.analytics.data_v1beta.types.BatchRunPivotReportsRequest, dict]]): The request object. The batch request containing multiple pivot report requests. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -537,11 +551,11 @@ async def sample_batch_run_pivot_reports(): async def get_metadata( self, - request: Union[analytics_data_api.GetMetadataRequest, dict] = None, + request: Optional[Union[analytics_data_api.GetMetadataRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.Metadata: r"""Returns metadata for dimensions and metrics available in @@ -583,7 +597,7 @@ async def sample_get_metadata(): print(response) Args: - request (Union[google.analytics.data_v1beta.types.GetMetadataRequest, dict]): + request (Optional[Union[google.analytics.data_v1beta.types.GetMetadataRequest, dict]]): The request object. Request for a property's dimension and metric metadata. name (:class:`str`): @@ -659,10 +673,12 @@ async def sample_get_metadata(): async def run_realtime_report( self, - request: Union[analytics_data_api.RunRealtimeReportRequest, dict] = None, + request: Optional[ + Union[analytics_data_api.RunRealtimeReportRequest, dict] + ] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.RunRealtimeReportResponse: r"""Returns a customized report of realtime event data for your @@ -702,7 +718,7 @@ async def sample_run_realtime_report(): print(response) Args: - request (Union[google.analytics.data_v1beta.types.RunRealtimeReportRequest, dict]): + request (Optional[Union[google.analytics.data_v1beta.types.RunRealtimeReportRequest, dict]]): The request object. The request to generate a realtime report. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -747,10 +763,12 @@ async def sample_run_realtime_report(): async def check_compatibility( self, - request: Union[analytics_data_api.CheckCompatibilityRequest, dict] = None, + request: Optional[ + Union[analytics_data_api.CheckCompatibilityRequest, dict] + ] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.CheckCompatibilityResponse: r"""This compatibility method lists dimensions and @@ -791,7 +809,7 @@ async def sample_check_compatibility(): print(response) Args: - request (Union[google.analytics.data_v1beta.types.CheckCompatibilityRequest, dict]): + request (Optional[Union[google.analytics.data_v1beta.types.CheckCompatibilityRequest, dict]]): The request object. The request for compatibility information for a report's dimensions and metrics. Check compatibility provides a preview of the compatibility of diff --git a/google/analytics/data_v1beta/services/beta_analytics_data/client.py b/google/analytics/data_v1beta/services/beta_analytics_data/client.py index 9153b45..f20db56 100644 --- a/google/analytics/data_v1beta/services/beta_analytics_data/client.py +++ b/google/analytics/data_v1beta/services/beta_analytics_data/client.py @@ -16,7 +16,18 @@ from collections import OrderedDict import os import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union, cast +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions @@ -59,7 +70,7 @@ class BetaAnalyticsDataClientMeta(type): def get_transport_class( cls, - label: str = None, + label: Optional[str] = None, ) -> Type[BetaAnalyticsDataTransport]: """Returns an appropriate transport class. @@ -327,7 +338,7 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, BetaAnalyticsDataTransport, None] = None, + transport: Optional[Union[str, BetaAnalyticsDataTransport]] = None, client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -428,10 +439,10 @@ def __init__( def run_report( self, - request: Union[analytics_data_api.RunReportRequest, dict] = None, + request: Optional[Union[analytics_data_api.RunReportRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.RunReportResponse: r"""Returns a customized report of your Google Analytics event data. @@ -518,10 +529,10 @@ def sample_run_report(): def run_pivot_report( self, - request: Union[analytics_data_api.RunPivotReportRequest, dict] = None, + request: Optional[Union[analytics_data_api.RunPivotReportRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.RunPivotReportResponse: r"""Returns a customized pivot report of your Google @@ -603,10 +614,12 @@ def sample_run_pivot_report(): def batch_run_reports( self, - request: Union[analytics_data_api.BatchRunReportsRequest, dict] = None, + request: Optional[ + Union[analytics_data_api.BatchRunReportsRequest, dict] + ] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.BatchRunReportsResponse: r"""Returns multiple reports in a batch. All reports must @@ -684,10 +697,12 @@ def sample_batch_run_reports(): def batch_run_pivot_reports( self, - request: Union[analytics_data_api.BatchRunPivotReportsRequest, dict] = None, + request: Optional[ + Union[analytics_data_api.BatchRunPivotReportsRequest, dict] + ] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.BatchRunPivotReportsResponse: r"""Returns multiple pivot reports in a batch. All @@ -765,11 +780,11 @@ def sample_batch_run_pivot_reports(): def get_metadata( self, - request: Union[analytics_data_api.GetMetadataRequest, dict] = None, + request: Optional[Union[analytics_data_api.GetMetadataRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.Metadata: r"""Returns metadata for dimensions and metrics available in @@ -887,10 +902,12 @@ def sample_get_metadata(): def run_realtime_report( self, - request: Union[analytics_data_api.RunRealtimeReportRequest, dict] = None, + request: Optional[ + Union[analytics_data_api.RunRealtimeReportRequest, dict] + ] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.RunRealtimeReportResponse: r"""Returns a customized report of realtime event data for your @@ -976,10 +993,12 @@ def sample_run_realtime_report(): def check_compatibility( self, - request: Union[analytics_data_api.CheckCompatibilityRequest, dict] = None, + request: Optional[ + Union[analytics_data_api.CheckCompatibilityRequest, dict] + ] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.CheckCompatibilityResponse: r"""This compatibility method lists dimensions and diff --git a/google/analytics/data_v1beta/services/beta_analytics_data/transports/base.py b/google/analytics/data_v1beta/services/beta_analytics_data/transports/base.py index 7fe6a32..6f710d1 100644 --- a/google/analytics/data_v1beta/services/beta_analytics_data/transports/base.py +++ b/google/analytics/data_v1beta/services/beta_analytics_data/transports/base.py @@ -51,7 +51,7 @@ def __init__( self, *, host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, diff --git a/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc.py b/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc.py index a95c7dc..7fba825 100644 --- a/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc.py +++ b/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc.py @@ -46,14 +46,14 @@ def __init__( self, *, host: str = "analyticsdata.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, @@ -180,8 +180,8 @@ def __init__( def create_channel( cls, host: str = "analyticsdata.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, diff --git a/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc_asyncio.py b/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc_asyncio.py index aac4267..6bc7689 100644 --- a/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc_asyncio.py +++ b/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc_asyncio.py @@ -48,7 +48,7 @@ class BetaAnalyticsDataGrpcAsyncIOTransport(BetaAnalyticsDataTransport): def create_channel( cls, host: str = "analyticsdata.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -91,15 +91,15 @@ def __init__( self, *, host: str = "analyticsdata.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, diff --git a/google/analytics/data_v1beta/services/beta_analytics_data/transports/rest.py b/google/analytics/data_v1beta/services/beta_analytics_data/transports/rest.py index 05ea767..248dee0 100644 --- a/google/analytics/data_v1beta/services/beta_analytics_data/transports/rest.py +++ b/google/analytics/data_v1beta/services/beta_analytics_data/transports/rest.py @@ -309,10 +309,10 @@ def __init__( self, *, host: str = "analyticsdata.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + 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, @@ -394,7 +394,7 @@ def __call__( request: analytics_data_api.BatchRunPivotReportsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.BatchRunPivotReportsResponse: r"""Call the batch run pivot reports method over HTTP. @@ -482,7 +482,7 @@ def __call__( request: analytics_data_api.BatchRunReportsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.BatchRunReportsResponse: r"""Call the batch run reports method over HTTP. @@ -570,7 +570,7 @@ def __call__( request: analytics_data_api.CheckCompatibilityRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.CheckCompatibilityResponse: r"""Call the check compatibility method over HTTP. @@ -672,7 +672,7 @@ def __call__( request: analytics_data_api.GetMetadataRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.Metadata: r"""Call the get metadata method over HTTP. @@ -750,7 +750,7 @@ def __call__( request: analytics_data_api.RunPivotReportRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.RunPivotReportResponse: r"""Call the run pivot report method over HTTP. @@ -838,7 +838,7 @@ def __call__( request: analytics_data_api.RunRealtimeReportRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.RunRealtimeReportResponse: r"""Call the run realtime report method over HTTP. @@ -926,7 +926,7 @@ def __call__( request: analytics_data_api.RunReportRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> analytics_data_api.RunReportResponse: r"""Call the run report method over HTTP. diff --git a/google/analytics/data_v1beta/types/analytics_data_api.py b/google/analytics/data_v1beta/types/analytics_data_api.py index 022fde9..d963379 100644 --- a/google/analytics/data_v1beta/types/analytics_data_api.py +++ b/google/analytics/data_v1beta/types/analytics_data_api.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore from google.analytics.data_v1beta.types import data @@ -58,10 +60,10 @@ class CheckCompatibilityRequest(proto.Message): dimensions and metrics common to all properties. In this special mode, this method will not return custom dimensions and metrics. - dimensions (Sequence[google.analytics.data_v1beta.types.Dimension]): + dimensions (MutableSequence[google.analytics.data_v1beta.types.Dimension]): The dimensions in this report. ``dimensions`` should be the same value as in your ``runReport`` request. - metrics (Sequence[google.analytics.data_v1beta.types.Metric]): + metrics (MutableSequence[google.analytics.data_v1beta.types.Metric]): The metrics in this report. ``metrics`` should be the same value as in your ``runReport`` request. dimension_filter (google.analytics.data_v1beta.types.FilterExpression): @@ -77,31 +79,31 @@ class CheckCompatibilityRequest(proto.Message): compatible dimensions & metrics. """ - property = proto.Field( + property: str = proto.Field( proto.STRING, number=1, ) - dimensions = proto.RepeatedField( + dimensions: MutableSequence[data.Dimension] = proto.RepeatedField( proto.MESSAGE, number=2, message=data.Dimension, ) - metrics = proto.RepeatedField( + metrics: MutableSequence[data.Metric] = proto.RepeatedField( proto.MESSAGE, number=3, message=data.Metric, ) - dimension_filter = proto.Field( + dimension_filter: data.FilterExpression = proto.Field( proto.MESSAGE, number=4, message=data.FilterExpression, ) - metric_filter = proto.Field( + metric_filter: data.FilterExpression = proto.Field( proto.MESSAGE, number=5, message=data.FilterExpression, ) - compatibility_filter = proto.Field( + compatibility_filter: data.Compatibility = proto.Field( proto.ENUM, number=6, enum=data.Compatibility, @@ -113,18 +115,22 @@ class CheckCompatibilityResponse(proto.Message): dimension & metric. Attributes: - dimension_compatibilities (Sequence[google.analytics.data_v1beta.types.DimensionCompatibility]): + dimension_compatibilities (MutableSequence[google.analytics.data_v1beta.types.DimensionCompatibility]): The compatibility of each dimension. - metric_compatibilities (Sequence[google.analytics.data_v1beta.types.MetricCompatibility]): + metric_compatibilities (MutableSequence[google.analytics.data_v1beta.types.MetricCompatibility]): The compatibility of each metric. """ - dimension_compatibilities = proto.RepeatedField( + dimension_compatibilities: MutableSequence[ + data.DimensionCompatibility + ] = proto.RepeatedField( proto.MESSAGE, number=1, message=data.DimensionCompatibility, ) - metric_compatibilities = proto.RepeatedField( + metric_compatibilities: MutableSequence[ + data.MetricCompatibility + ] = proto.RepeatedField( proto.MESSAGE, number=2, message=data.MetricCompatibility, @@ -138,22 +144,22 @@ class Metadata(proto.Message): Attributes: name (str): Resource name of this metadata. - dimensions (Sequence[google.analytics.data_v1beta.types.DimensionMetadata]): + dimensions (MutableSequence[google.analytics.data_v1beta.types.DimensionMetadata]): The dimension descriptions. - metrics (Sequence[google.analytics.data_v1beta.types.MetricMetadata]): + metrics (MutableSequence[google.analytics.data_v1beta.types.MetricMetadata]): The metric descriptions. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=3, ) - dimensions = proto.RepeatedField( + dimensions: MutableSequence[data.DimensionMetadata] = proto.RepeatedField( proto.MESSAGE, number=1, message=data.DimensionMetadata, ) - metrics = proto.RepeatedField( + metrics: MutableSequence[data.MetricMetadata] = proto.RepeatedField( proto.MESSAGE, number=2, message=data.MetricMetadata, @@ -173,11 +179,11 @@ class RunReportRequest(proto.Message): unspecified or consistent with the batch-level property. Example: properties/1234 - dimensions (Sequence[google.analytics.data_v1beta.types.Dimension]): + dimensions (MutableSequence[google.analytics.data_v1beta.types.Dimension]): The dimensions requested and displayed. - metrics (Sequence[google.analytics.data_v1beta.types.Metric]): + metrics (MutableSequence[google.analytics.data_v1beta.types.Metric]): The metrics requested and displayed. - date_ranges (Sequence[google.analytics.data_v1beta.types.DateRange]): + date_ranges (MutableSequence[google.analytics.data_v1beta.types.DateRange]): Date ranges of data 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 event data for @@ -222,11 +228,11 @@ class RunReportRequest(proto.Message): To learn more about this pagination parameter, see `Pagination `__. - metric_aggregations (Sequence[google.analytics.data_v1beta.types.MetricAggregation]): + metric_aggregations (MutableSequence[google.analytics.data_v1beta.types.MetricAggregation]): Aggregation of metrics. Aggregated metric values will be shown in rows where the dimension_values are set to "RESERVED_(MetricAggregation)". - order_bys (Sequence[google.analytics.data_v1beta.types.OrderBy]): + order_bys (MutableSequence[google.analytics.data_v1beta.types.OrderBy]): Specifies how rows are ordered in the response. currency_code (str): @@ -248,67 +254,67 @@ class RunReportRequest(proto.Message): `PropertyQuota <#PropertyQuota>`__. """ - property = proto.Field( + property: str = proto.Field( proto.STRING, number=1, ) - dimensions = proto.RepeatedField( + dimensions: MutableSequence[data.Dimension] = proto.RepeatedField( proto.MESSAGE, number=2, message=data.Dimension, ) - metrics = proto.RepeatedField( + metrics: MutableSequence[data.Metric] = proto.RepeatedField( proto.MESSAGE, number=3, message=data.Metric, ) - date_ranges = proto.RepeatedField( + date_ranges: MutableSequence[data.DateRange] = proto.RepeatedField( proto.MESSAGE, number=4, message=data.DateRange, ) - dimension_filter = proto.Field( + dimension_filter: data.FilterExpression = proto.Field( proto.MESSAGE, number=5, message=data.FilterExpression, ) - metric_filter = proto.Field( + metric_filter: data.FilterExpression = proto.Field( proto.MESSAGE, number=6, message=data.FilterExpression, ) - offset = proto.Field( + offset: int = proto.Field( proto.INT64, number=7, ) - limit = proto.Field( + limit: int = proto.Field( proto.INT64, number=8, ) - metric_aggregations = proto.RepeatedField( + metric_aggregations: MutableSequence[data.MetricAggregation] = proto.RepeatedField( proto.ENUM, number=9, enum=data.MetricAggregation, ) - order_bys = proto.RepeatedField( + order_bys: MutableSequence[data.OrderBy] = proto.RepeatedField( proto.MESSAGE, number=10, message=data.OrderBy, ) - currency_code = proto.Field( + currency_code: str = proto.Field( proto.STRING, number=11, ) - cohort_spec = proto.Field( + cohort_spec: data.CohortSpec = proto.Field( proto.MESSAGE, number=12, message=data.CohortSpec, ) - keep_empty_rows = proto.Field( + keep_empty_rows: bool = proto.Field( proto.BOOL, number=13, ) - return_property_quota = proto.Field( + return_property_quota: bool = proto.Field( proto.BOOL, number=14, ) @@ -318,23 +324,23 @@ class RunReportResponse(proto.Message): r"""The response report table corresponding to a request. Attributes: - dimension_headers (Sequence[google.analytics.data_v1beta.types.DimensionHeader]): + dimension_headers (MutableSequence[google.analytics.data_v1beta.types.DimensionHeader]): Describes dimension columns. The number of DimensionHeaders and ordering of DimensionHeaders matches the dimensions present in rows. - metric_headers (Sequence[google.analytics.data_v1beta.types.MetricHeader]): + metric_headers (MutableSequence[google.analytics.data_v1beta.types.MetricHeader]): Describes metric columns. The number of MetricHeaders and ordering of MetricHeaders matches the metrics present in rows. - rows (Sequence[google.analytics.data_v1beta.types.Row]): + rows (MutableSequence[google.analytics.data_v1beta.types.Row]): Rows of dimension value combinations and metric values in the report. - totals (Sequence[google.analytics.data_v1beta.types.Row]): + totals (MutableSequence[google.analytics.data_v1beta.types.Row]): If requested, the totaled values of metrics. - maximums (Sequence[google.analytics.data_v1beta.types.Row]): + maximums (MutableSequence[google.analytics.data_v1beta.types.Row]): If requested, the maximum values of metrics. - minimums (Sequence[google.analytics.data_v1beta.types.Row]): + minimums (MutableSequence[google.analytics.data_v1beta.types.Row]): If requested, the minimum values of metrics. row_count (int): The total number of rows in the query result. ``rowCount`` @@ -359,51 +365,51 @@ class RunReportResponse(proto.Message): response types in JSON. """ - dimension_headers = proto.RepeatedField( + dimension_headers: MutableSequence[data.DimensionHeader] = proto.RepeatedField( proto.MESSAGE, number=1, message=data.DimensionHeader, ) - metric_headers = proto.RepeatedField( + metric_headers: MutableSequence[data.MetricHeader] = proto.RepeatedField( proto.MESSAGE, number=2, message=data.MetricHeader, ) - rows = proto.RepeatedField( + rows: MutableSequence[data.Row] = proto.RepeatedField( proto.MESSAGE, number=3, message=data.Row, ) - totals = proto.RepeatedField( + totals: MutableSequence[data.Row] = proto.RepeatedField( proto.MESSAGE, number=4, message=data.Row, ) - maximums = proto.RepeatedField( + maximums: MutableSequence[data.Row] = proto.RepeatedField( proto.MESSAGE, number=5, message=data.Row, ) - minimums = proto.RepeatedField( + minimums: MutableSequence[data.Row] = proto.RepeatedField( proto.MESSAGE, number=6, message=data.Row, ) - row_count = proto.Field( + row_count: int = proto.Field( proto.INT32, number=7, ) - metadata = proto.Field( + metadata: data.ResponseMetaData = proto.Field( proto.MESSAGE, number=8, message=data.ResponseMetaData, ) - property_quota = proto.Field( + property_quota: data.PropertyQuota = proto.Field( proto.MESSAGE, number=9, message=data.PropertyQuota, ) - kind = proto.Field( + kind: str = proto.Field( proto.STRING, number=10, ) @@ -422,15 +428,15 @@ class RunPivotReportRequest(proto.Message): unspecified or consistent with the batch-level property. Example: properties/1234 - dimensions (Sequence[google.analytics.data_v1beta.types.Dimension]): + dimensions (MutableSequence[google.analytics.data_v1beta.types.Dimension]): The dimensions requested. All defined dimensions must be used by one of the following: dimension_expression, dimension_filter, pivots, order_bys. - metrics (Sequence[google.analytics.data_v1beta.types.Metric]): + metrics (MutableSequence[google.analytics.data_v1beta.types.Metric]): The metrics requested, at least one metric needs to be specified. All defined metrics must be used by one of the following: metric_expression, metric_filter, order_bys. - date_ranges (Sequence[google.analytics.data_v1beta.types.DateRange]): + date_ranges (MutableSequence[google.analytics.data_v1beta.types.DateRange]): The date range to retrieve event data for the report. If multiple date ranges are specified, event data from each date range is used in the report. A special dimension with @@ -438,7 +444,7 @@ class RunPivotReportRequest(proto.Message): names; if included, the report compares between date ranges. In a cohort request, this ``dateRanges`` must be unspecified. - pivots (Sequence[google.analytics.data_v1beta.types.Pivot]): + pivots (MutableSequence[google.analytics.data_v1beta.types.Pivot]): Describes the visual format of the report's dimensions in columns or rows. The union of the fieldNames (dimension names) in all pivots must @@ -475,54 +481,54 @@ class RunPivotReportRequest(proto.Message): `PropertyQuota <#PropertyQuota>`__. """ - property = proto.Field( + property: str = proto.Field( proto.STRING, number=1, ) - dimensions = proto.RepeatedField( + dimensions: MutableSequence[data.Dimension] = proto.RepeatedField( proto.MESSAGE, number=2, message=data.Dimension, ) - metrics = proto.RepeatedField( + metrics: MutableSequence[data.Metric] = proto.RepeatedField( proto.MESSAGE, number=3, message=data.Metric, ) - date_ranges = proto.RepeatedField( + date_ranges: MutableSequence[data.DateRange] = proto.RepeatedField( proto.MESSAGE, number=4, message=data.DateRange, ) - pivots = proto.RepeatedField( + pivots: MutableSequence[data.Pivot] = proto.RepeatedField( proto.MESSAGE, number=5, message=data.Pivot, ) - dimension_filter = proto.Field( + dimension_filter: data.FilterExpression = proto.Field( proto.MESSAGE, number=6, message=data.FilterExpression, ) - metric_filter = proto.Field( + metric_filter: data.FilterExpression = proto.Field( proto.MESSAGE, number=7, message=data.FilterExpression, ) - currency_code = proto.Field( + currency_code: str = proto.Field( proto.STRING, number=8, ) - cohort_spec = proto.Field( + cohort_spec: data.CohortSpec = proto.Field( proto.MESSAGE, number=9, message=data.CohortSpec, ) - keep_empty_rows = proto.Field( + keep_empty_rows: bool = proto.Field( proto.BOOL, number=10, ) - return_property_quota = proto.Field( + return_property_quota: bool = proto.Field( proto.BOOL, number=11, ) @@ -533,7 +539,7 @@ class RunPivotReportResponse(proto.Message): request. Attributes: - pivot_headers (Sequence[google.analytics.data_v1beta.types.PivotHeader]): + pivot_headers (MutableSequence[google.analytics.data_v1beta.types.PivotHeader]): Summarizes the columns and rows created by a pivot. Each pivot in the request produces one header in the response. If we have a request like this: @@ -574,19 +580,19 @@ class RunPivotReportResponse(proto.Message): "dimensionValues": [{ "value": "scroll" }] }] }] - dimension_headers (Sequence[google.analytics.data_v1beta.types.DimensionHeader]): + dimension_headers (MutableSequence[google.analytics.data_v1beta.types.DimensionHeader]): Describes dimension columns. The number of DimensionHeaders and ordering of DimensionHeaders matches the dimensions present in rows. - metric_headers (Sequence[google.analytics.data_v1beta.types.MetricHeader]): + metric_headers (MutableSequence[google.analytics.data_v1beta.types.MetricHeader]): Describes metric columns. The number of MetricHeaders and ordering of MetricHeaders matches the metrics present in rows. - rows (Sequence[google.analytics.data_v1beta.types.Row]): + rows (MutableSequence[google.analytics.data_v1beta.types.Row]): Rows of dimension value combinations and metric values in the report. - aggregates (Sequence[google.analytics.data_v1beta.types.Row]): + aggregates (MutableSequence[google.analytics.data_v1beta.types.Row]): Aggregation of metric values. Can be totals, minimums, or maximums. The returned aggregations are controlled by the metric_aggregations in the pivot. The type of aggregation @@ -604,42 +610,42 @@ class RunPivotReportResponse(proto.Message): between response types in JSON. """ - pivot_headers = proto.RepeatedField( + pivot_headers: MutableSequence[data.PivotHeader] = proto.RepeatedField( proto.MESSAGE, number=1, message=data.PivotHeader, ) - dimension_headers = proto.RepeatedField( + dimension_headers: MutableSequence[data.DimensionHeader] = proto.RepeatedField( proto.MESSAGE, number=2, message=data.DimensionHeader, ) - metric_headers = proto.RepeatedField( + metric_headers: MutableSequence[data.MetricHeader] = proto.RepeatedField( proto.MESSAGE, number=3, message=data.MetricHeader, ) - rows = proto.RepeatedField( + rows: MutableSequence[data.Row] = proto.RepeatedField( proto.MESSAGE, number=4, message=data.Row, ) - aggregates = proto.RepeatedField( + aggregates: MutableSequence[data.Row] = proto.RepeatedField( proto.MESSAGE, number=5, message=data.Row, ) - metadata = proto.Field( + metadata: data.ResponseMetaData = proto.Field( proto.MESSAGE, number=6, message=data.ResponseMetaData, ) - property_quota = proto.Field( + property_quota: data.PropertyQuota = proto.Field( proto.MESSAGE, number=7, message=data.PropertyQuota, ) - kind = proto.Field( + kind: str = proto.Field( proto.STRING, number=8, ) @@ -659,17 +665,17 @@ class BatchRunReportsRequest(proto.Message): consistent with this property. Example: properties/1234 - requests (Sequence[google.analytics.data_v1beta.types.RunReportRequest]): + requests (MutableSequence[google.analytics.data_v1beta.types.RunReportRequest]): Individual requests. Each request has a separate report response. Each batch request is allowed up to 5 requests. """ - property = proto.Field( + property: str = proto.Field( proto.STRING, number=1, ) - requests = proto.RepeatedField( + requests: MutableSequence["RunReportRequest"] = proto.RepeatedField( proto.MESSAGE, number=2, message="RunReportRequest", @@ -680,7 +686,7 @@ class BatchRunReportsResponse(proto.Message): r"""The batch response containing multiple reports. Attributes: - reports (Sequence[google.analytics.data_v1beta.types.RunReportResponse]): + reports (MutableSequence[google.analytics.data_v1beta.types.RunReportResponse]): Individual responses. Each response has a separate report request. kind (str): @@ -690,12 +696,12 @@ class BatchRunReportsResponse(proto.Message): between response types in JSON. """ - reports = proto.RepeatedField( + reports: MutableSequence["RunReportResponse"] = proto.RepeatedField( proto.MESSAGE, number=1, message="RunReportResponse", ) - kind = proto.Field( + kind: str = proto.Field( proto.STRING, number=2, ) @@ -715,17 +721,17 @@ class BatchRunPivotReportsRequest(proto.Message): consistent with this property. Example: properties/1234 - requests (Sequence[google.analytics.data_v1beta.types.RunPivotReportRequest]): + requests (MutableSequence[google.analytics.data_v1beta.types.RunPivotReportRequest]): Individual requests. Each request has a separate pivot report response. Each batch request is allowed up to 5 requests. """ - property = proto.Field( + property: str = proto.Field( proto.STRING, number=1, ) - requests = proto.RepeatedField( + requests: MutableSequence["RunPivotReportRequest"] = proto.RepeatedField( proto.MESSAGE, number=2, message="RunPivotReportRequest", @@ -736,7 +742,7 @@ class BatchRunPivotReportsResponse(proto.Message): r"""The batch response containing multiple pivot reports. Attributes: - pivot_reports (Sequence[google.analytics.data_v1beta.types.RunPivotReportResponse]): + pivot_reports (MutableSequence[google.analytics.data_v1beta.types.RunPivotReportResponse]): Individual responses. Each response has a separate pivot report request. kind (str): @@ -746,12 +752,12 @@ class BatchRunPivotReportsResponse(proto.Message): between response types in JSON. """ - pivot_reports = proto.RepeatedField( + pivot_reports: MutableSequence["RunPivotReportResponse"] = proto.RepeatedField( proto.MESSAGE, number=1, message="RunPivotReportResponse", ) - kind = proto.Field( + kind: str = proto.Field( proto.STRING, number=2, ) @@ -776,7 +782,7 @@ class GetMetadataRequest(proto.Message): not return custom dimensions and metrics. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -793,9 +799,9 @@ class RunRealtimeReportRequest(proto.Message): ID `__. Example: properties/1234 - dimensions (Sequence[google.analytics.data_v1beta.types.Dimension]): + dimensions (MutableSequence[google.analytics.data_v1beta.types.Dimension]): The dimensions requested and displayed. - metrics (Sequence[google.analytics.data_v1beta.types.Metric]): + metrics (MutableSequence[google.analytics.data_v1beta.types.Metric]): The metrics requested and displayed. dimension_filter (google.analytics.data_v1beta.types.FilterExpression): The filter clause of dimensions. Metrics @@ -816,18 +822,18 @@ class RunRealtimeReportRequest(proto.Message): 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. - metric_aggregations (Sequence[google.analytics.data_v1beta.types.MetricAggregation]): + metric_aggregations (MutableSequence[google.analytics.data_v1beta.types.MetricAggregation]): Aggregation of metrics. Aggregated metric values will be shown in rows where the dimension_values are set to "RESERVED_(MetricAggregation)". - order_bys (Sequence[google.analytics.data_v1beta.types.OrderBy]): + order_bys (MutableSequence[google.analytics.data_v1beta.types.OrderBy]): Specifies how rows are ordered in the response. return_property_quota (bool): Toggles whether to return the current state of this Analytics Property's Realtime quota. Quota is returned in `PropertyQuota <#PropertyQuota>`__. - minute_ranges (Sequence[google.analytics.data_v1beta.types.MinuteRange]): + minute_ranges (MutableSequence[google.analytics.data_v1beta.types.MinuteRange]): The minute ranges of event data to read. If unspecified, one minute range for the last 30 minutes will be used. If multiple minute ranges @@ -838,49 +844,49 @@ class RunRealtimeReportRequest(proto.Message): rows for both minute ranges. """ - property = proto.Field( + property: str = proto.Field( proto.STRING, number=1, ) - dimensions = proto.RepeatedField( + dimensions: MutableSequence[data.Dimension] = proto.RepeatedField( proto.MESSAGE, number=2, message=data.Dimension, ) - metrics = proto.RepeatedField( + metrics: MutableSequence[data.Metric] = proto.RepeatedField( proto.MESSAGE, number=3, message=data.Metric, ) - dimension_filter = proto.Field( + dimension_filter: data.FilterExpression = proto.Field( proto.MESSAGE, number=4, message=data.FilterExpression, ) - metric_filter = proto.Field( + metric_filter: data.FilterExpression = proto.Field( proto.MESSAGE, number=5, message=data.FilterExpression, ) - limit = proto.Field( + limit: int = proto.Field( proto.INT64, number=6, ) - metric_aggregations = proto.RepeatedField( + metric_aggregations: MutableSequence[data.MetricAggregation] = proto.RepeatedField( proto.ENUM, number=7, enum=data.MetricAggregation, ) - order_bys = proto.RepeatedField( + order_bys: MutableSequence[data.OrderBy] = proto.RepeatedField( proto.MESSAGE, number=8, message=data.OrderBy, ) - return_property_quota = proto.Field( + return_property_quota: bool = proto.Field( proto.BOOL, number=9, ) - minute_ranges = proto.RepeatedField( + minute_ranges: MutableSequence[data.MinuteRange] = proto.RepeatedField( proto.MESSAGE, number=10, message=data.MinuteRange, @@ -892,23 +898,23 @@ class RunRealtimeReportResponse(proto.Message): request. Attributes: - dimension_headers (Sequence[google.analytics.data_v1beta.types.DimensionHeader]): + dimension_headers (MutableSequence[google.analytics.data_v1beta.types.DimensionHeader]): Describes dimension columns. The number of DimensionHeaders and ordering of DimensionHeaders matches the dimensions present in rows. - metric_headers (Sequence[google.analytics.data_v1beta.types.MetricHeader]): + metric_headers (MutableSequence[google.analytics.data_v1beta.types.MetricHeader]): Describes metric columns. The number of MetricHeaders and ordering of MetricHeaders matches the metrics present in rows. - rows (Sequence[google.analytics.data_v1beta.types.Row]): + rows (MutableSequence[google.analytics.data_v1beta.types.Row]): Rows of dimension value combinations and metric values in the report. - totals (Sequence[google.analytics.data_v1beta.types.Row]): + totals (MutableSequence[google.analytics.data_v1beta.types.Row]): If requested, the totaled values of metrics. - maximums (Sequence[google.analytics.data_v1beta.types.Row]): + maximums (MutableSequence[google.analytics.data_v1beta.types.Row]): If requested, the maximum values of metrics. - minimums (Sequence[google.analytics.data_v1beta.types.Row]): + minimums (MutableSequence[google.analytics.data_v1beta.types.Row]): If requested, the minimum values of metrics. row_count (int): The total number of rows in the query result. ``rowCount`` @@ -927,46 +933,46 @@ class RunRealtimeReportResponse(proto.Message): between response types in JSON. """ - dimension_headers = proto.RepeatedField( + dimension_headers: MutableSequence[data.DimensionHeader] = proto.RepeatedField( proto.MESSAGE, number=1, message=data.DimensionHeader, ) - metric_headers = proto.RepeatedField( + metric_headers: MutableSequence[data.MetricHeader] = proto.RepeatedField( proto.MESSAGE, number=2, message=data.MetricHeader, ) - rows = proto.RepeatedField( + rows: MutableSequence[data.Row] = proto.RepeatedField( proto.MESSAGE, number=3, message=data.Row, ) - totals = proto.RepeatedField( + totals: MutableSequence[data.Row] = proto.RepeatedField( proto.MESSAGE, number=4, message=data.Row, ) - maximums = proto.RepeatedField( + maximums: MutableSequence[data.Row] = proto.RepeatedField( proto.MESSAGE, number=5, message=data.Row, ) - minimums = proto.RepeatedField( + minimums: MutableSequence[data.Row] = proto.RepeatedField( proto.MESSAGE, number=6, message=data.Row, ) - row_count = proto.Field( + row_count: int = proto.Field( proto.INT32, number=7, ) - property_quota = proto.Field( + property_quota: data.PropertyQuota = proto.Field( proto.MESSAGE, number=8, message=data.PropertyQuota, ) - kind = proto.Field( + kind: str = proto.Field( proto.STRING, number=9, ) diff --git a/google/analytics/data_v1beta/types/data.py b/google/analytics/data_v1beta/types/data.py index 20ec7ae..0a58cd8 100644 --- a/google/analytics/data_v1beta/types/data.py +++ b/google/analytics/data_v1beta/types/data.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore __protobuf__ = proto.module( @@ -122,15 +124,15 @@ class DateRange(proto.Message): in the request: ``date_range_0``, ``date_range_1``, etc. """ - start_date = proto.Field( + start_date: str = proto.Field( proto.STRING, number=1, ) - end_date = proto.Field( + end_date: str = proto.Field( proto.STRING, number=2, ) - name = proto.Field( + name: str = proto.Field( proto.STRING, number=3, ) @@ -177,17 +179,17 @@ class MinuteRange(proto.Message): etc. """ - start_minutes_ago = proto.Field( + start_minutes_ago: int = proto.Field( proto.INT32, number=1, optional=True, ) - end_minutes_ago = proto.Field( + end_minutes_ago: int = proto.Field( proto.INT32, number=2, optional=True, ) - name = proto.Field( + name: str = proto.Field( proto.STRING, number=3, ) @@ -223,11 +225,11 @@ class Dimension(proto.Message): ", ", city). """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - dimension_expression = proto.Field( + dimension_expression: "DimensionExpression" = proto.Field( proto.MESSAGE, number=2, message="DimensionExpression", @@ -276,7 +278,7 @@ class CaseExpression(proto.Message): to a name in dimensions field of the request. """ - dimension_name = proto.Field( + dimension_name: str = proto.Field( proto.STRING, number=1, ) @@ -285,7 +287,7 @@ class ConcatenateExpression(proto.Message): r"""Used to combine dimension values to a single dimension. Attributes: - dimension_names (Sequence[str]): + dimension_names (MutableSequence[str]): Names of dimensions. The names must refer back to names in the dimensions field of the request. @@ -300,28 +302,28 @@ class ConcatenateExpression(proto.Message): response will contain "US,FR,JP". """ - dimension_names = proto.RepeatedField( + dimension_names: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=1, ) - delimiter = proto.Field( + delimiter: str = proto.Field( proto.STRING, number=2, ) - lower_case = proto.Field( + lower_case: CaseExpression = proto.Field( proto.MESSAGE, number=4, oneof="one_expression", message=CaseExpression, ) - upper_case = proto.Field( + upper_case: CaseExpression = proto.Field( proto.MESSAGE, number=5, oneof="one_expression", message=CaseExpression, ) - concatenate = proto.Field( + concatenate: ConcatenateExpression = proto.Field( proto.MESSAGE, number=6, oneof="one_expression", @@ -360,15 +362,15 @@ class Metric(proto.Message): ``orderBys``, or a metric ``expression``. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - expression = proto.Field( + expression: str = proto.Field( proto.STRING, number=2, ) - invisible = proto.Field( + invisible: bool = proto.Field( proto.BOOL, number=3, ) @@ -408,25 +410,25 @@ class FilterExpression(proto.Message): This field is a member of `oneof`_ ``expr``. """ - and_group = proto.Field( + and_group: "FilterExpressionList" = proto.Field( proto.MESSAGE, number=1, oneof="expr", message="FilterExpressionList", ) - or_group = proto.Field( + or_group: "FilterExpressionList" = proto.Field( proto.MESSAGE, number=2, oneof="expr", message="FilterExpressionList", ) - not_expression = proto.Field( + not_expression: "FilterExpression" = proto.Field( proto.MESSAGE, number=3, oneof="expr", message="FilterExpression", ) - filter = proto.Field( + filter: "Filter" = proto.Field( proto.MESSAGE, number=4, oneof="expr", @@ -438,11 +440,11 @@ class FilterExpressionList(proto.Message): r"""A list of filter expressions. Attributes: - expressions (Sequence[google.analytics.data_v1beta.types.FilterExpression]): + expressions (MutableSequence[google.analytics.data_v1beta.types.FilterExpression]): A list of filter expressions. """ - expressions = proto.RepeatedField( + expressions: MutableSequence["FilterExpression"] = proto.RepeatedField( proto.MESSAGE, number=1, message="FilterExpression", @@ -507,16 +509,16 @@ class MatchType(proto.Enum): FULL_REGEXP = 5 PARTIAL_REGEXP = 6 - match_type = proto.Field( + match_type: "Filter.StringFilter.MatchType" = proto.Field( proto.ENUM, number=1, enum="Filter.StringFilter.MatchType", ) - value = proto.Field( + value: str = proto.Field( proto.STRING, number=2, ) - case_sensitive = proto.Field( + case_sensitive: bool = proto.Field( proto.BOOL, number=3, ) @@ -525,18 +527,18 @@ class InListFilter(proto.Message): r"""The result needs to be in a list of string values. Attributes: - values (Sequence[str]): + values (MutableSequence[str]): The list of string values. Must be non-empty. case_sensitive (bool): If true, the string value is case sensitive. """ - values = proto.RepeatedField( + values: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=1, ) - case_sensitive = proto.Field( + case_sensitive: bool = proto.Field( proto.BOOL, number=2, ) @@ -560,12 +562,12 @@ class Operation(proto.Enum): GREATER_THAN = 4 GREATER_THAN_OR_EQUAL = 5 - operation = proto.Field( + operation: "Filter.NumericFilter.Operation" = proto.Field( proto.ENUM, number=1, enum="Filter.NumericFilter.Operation", ) - value = proto.Field( + value: "NumericValue" = proto.Field( proto.MESSAGE, number=2, message="NumericValue", @@ -582,40 +584,40 @@ class BetweenFilter(proto.Message): Ends with this number. """ - from_value = proto.Field( + from_value: "NumericValue" = proto.Field( proto.MESSAGE, number=1, message="NumericValue", ) - to_value = proto.Field( + to_value: "NumericValue" = proto.Field( proto.MESSAGE, number=2, message="NumericValue", ) - field_name = proto.Field( + field_name: str = proto.Field( proto.STRING, number=1, ) - string_filter = proto.Field( + string_filter: StringFilter = proto.Field( proto.MESSAGE, number=3, oneof="one_filter", message=StringFilter, ) - in_list_filter = proto.Field( + in_list_filter: InListFilter = proto.Field( proto.MESSAGE, number=4, oneof="one_filter", message=InListFilter, ) - numeric_filter = proto.Field( + numeric_filter: NumericFilter = proto.Field( proto.MESSAGE, number=5, oneof="one_filter", message=NumericFilter, ) - between_filter = proto.Field( + between_filter: BetweenFilter = proto.Field( proto.MESSAGE, number=6, oneof="one_filter", @@ -662,7 +664,7 @@ class MetricOrderBy(proto.Message): A metric name in the request to order by. """ - metric_name = proto.Field( + metric_name: str = proto.Field( proto.STRING, number=1, ) @@ -685,11 +687,11 @@ class OrderType(proto.Enum): CASE_INSENSITIVE_ALPHANUMERIC = 2 NUMERIC = 3 - dimension_name = proto.Field( + dimension_name: str = proto.Field( proto.STRING, number=1, ) - order_type = proto.Field( + order_type: "OrderBy.DimensionOrderBy.OrderType" = proto.Field( proto.ENUM, number=2, enum="OrderBy.DimensionOrderBy.OrderType", @@ -703,7 +705,7 @@ class PivotOrderBy(proto.Message): In the response to order by, order rows by this column. Must be a metric name from the request. - pivot_selections (Sequence[google.analytics.data_v1beta.types.OrderBy.PivotOrderBy.PivotSelection]): + pivot_selections (MutableSequence[google.analytics.data_v1beta.types.OrderBy.PivotOrderBy.PivotSelection]): Used to select a dimension name and value pivot. If multiple pivot selections are given, the sort occurs on rows where all pivot @@ -739,44 +741,46 @@ class PivotSelection(proto.Message): this value. """ - dimension_name = proto.Field( + dimension_name: str = proto.Field( proto.STRING, number=1, ) - dimension_value = proto.Field( + dimension_value: str = proto.Field( proto.STRING, number=2, ) - metric_name = proto.Field( + metric_name: str = proto.Field( proto.STRING, number=1, ) - pivot_selections = proto.RepeatedField( + pivot_selections: MutableSequence[ + "OrderBy.PivotOrderBy.PivotSelection" + ] = proto.RepeatedField( proto.MESSAGE, number=2, message="OrderBy.PivotOrderBy.PivotSelection", ) - metric = proto.Field( + metric: MetricOrderBy = proto.Field( proto.MESSAGE, number=1, oneof="one_order_by", message=MetricOrderBy, ) - dimension = proto.Field( + dimension: DimensionOrderBy = proto.Field( proto.MESSAGE, number=2, oneof="one_order_by", message=DimensionOrderBy, ) - pivot = proto.Field( + pivot: PivotOrderBy = proto.Field( proto.MESSAGE, number=3, oneof="one_order_by", message=PivotOrderBy, ) - desc = proto.Field( + desc: bool = proto.Field( proto.BOOL, number=4, ) @@ -787,14 +791,14 @@ class Pivot(proto.Message): report response. Attributes: - field_names (Sequence[str]): + field_names (MutableSequence[str]): Dimension names for visible columns in the report response. Including "dateRange" produces a date range column; for each row in the response, dimension values in the date range column will indicate the corresponding date range from the request. - order_bys (Sequence[google.analytics.data_v1beta.types.OrderBy]): + order_bys (MutableSequence[google.analytics.data_v1beta.types.OrderBy]): Specifies how dimensions are ordered in the pivot. In the first Pivot, the OrderBys determine Row and PivotDimensionHeader ordering; in subsequent Pivots, the @@ -813,29 +817,29 @@ class Pivot(proto.Message): ``RunPivotReportRequest`` must not exceed 100,000. For example, a two pivot request with ``limit: 1000`` in each pivot will fail because the product is ``1,000,000``. - metric_aggregations (Sequence[google.analytics.data_v1beta.types.MetricAggregation]): + metric_aggregations (MutableSequence[google.analytics.data_v1beta.types.MetricAggregation]): Aggregate the metrics by dimensions in this pivot using the specified metric_aggregations. """ - field_names = proto.RepeatedField( + field_names: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=1, ) - order_bys = proto.RepeatedField( + order_bys: MutableSequence["OrderBy"] = proto.RepeatedField( proto.MESSAGE, number=2, message="OrderBy", ) - offset = proto.Field( + offset: int = proto.Field( proto.INT64, number=3, ) - limit = proto.Field( + limit: int = proto.Field( proto.INT64, number=4, ) - metric_aggregations = proto.RepeatedField( + metric_aggregations: MutableSequence["MetricAggregation"] = proto.RepeatedField( proto.ENUM, number=5, enum="MetricAggregation", @@ -863,7 +867,7 @@ class CohortSpec(proto.Message): separate rows in the report. Attributes: - cohorts (Sequence[google.analytics.data_v1beta.types.Cohort]): + cohorts (MutableSequence[google.analytics.data_v1beta.types.Cohort]): Defines the selection criteria to group users into cohorts. Most cohort reports define only a single cohort. @@ -878,17 +882,17 @@ class CohortSpec(proto.Message): Optional settings for a cohort report. """ - cohorts = proto.RepeatedField( + cohorts: MutableSequence["Cohort"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Cohort", ) - cohorts_range = proto.Field( + cohorts_range: "CohortsRange" = proto.Field( proto.MESSAGE, number=2, message="CohortsRange", ) - cohort_report_settings = proto.Field( + cohort_report_settings: "CohortReportSettings" = proto.Field( proto.MESSAGE, number=3, message="CohortReportSettings", @@ -934,15 +938,15 @@ class Cohort(proto.Message): month. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - dimension = proto.Field( + dimension: str = proto.Field( proto.STRING, number=2, ) - date_range = proto.Field( + date_range: "DateRange" = proto.Field( proto.MESSAGE, number=3, message="DateRange", @@ -1005,16 +1009,16 @@ class Granularity(proto.Enum): WEEKLY = 2 MONTHLY = 3 - granularity = proto.Field( + granularity: Granularity = proto.Field( proto.ENUM, number=1, enum=Granularity, ) - start_offset = proto.Field( + start_offset: int = proto.Field( proto.INT32, number=2, ) - end_offset = proto.Field( + end_offset: int = proto.Field( proto.INT32, number=3, ) @@ -1029,7 +1033,7 @@ class CohortReportSettings(proto.Message): end day. Not supported in ``RunReportRequest``. """ - accumulate = proto.Field( + accumulate: bool = proto.Field( proto.BOOL, number=1, ) @@ -1099,7 +1103,7 @@ class SchemaRestrictionResponse(proto.Message): management `__. Attributes: - active_metric_restrictions (Sequence[google.analytics.data_v1beta.types.ResponseMetaData.SchemaRestrictionResponse.ActiveMetricRestriction]): + active_metric_restrictions (MutableSequence[google.analytics.data_v1beta.types.ResponseMetaData.SchemaRestrictionResponse.ActiveMetricRestriction]): All restrictions actively enforced in creating the report. For example, ``purchaseRevenue`` always has the restriction type ``REVENUE_DATA``. However, this active response @@ -1115,53 +1119,57 @@ class ActiveMetricRestriction(proto.Message): The name of the restricted metric. This field is a member of `oneof`_ ``_metric_name``. - restricted_metric_types (Sequence[google.analytics.data_v1beta.types.RestrictedMetricType]): + restricted_metric_types (MutableSequence[google.analytics.data_v1beta.types.RestrictedMetricType]): The reason for this metric's restriction. """ - metric_name = proto.Field( + metric_name: str = proto.Field( proto.STRING, number=1, optional=True, ) - restricted_metric_types = proto.RepeatedField( + restricted_metric_types: MutableSequence[ + "RestrictedMetricType" + ] = proto.RepeatedField( proto.ENUM, number=2, enum="RestrictedMetricType", ) - active_metric_restrictions = proto.RepeatedField( + active_metric_restrictions: MutableSequence[ + "ResponseMetaData.SchemaRestrictionResponse.ActiveMetricRestriction" + ] = proto.RepeatedField( proto.MESSAGE, number=1, message="ResponseMetaData.SchemaRestrictionResponse.ActiveMetricRestriction", ) - data_loss_from_other_row = proto.Field( + data_loss_from_other_row: bool = proto.Field( proto.BOOL, number=3, ) - schema_restriction_response = proto.Field( + schema_restriction_response: SchemaRestrictionResponse = proto.Field( proto.MESSAGE, number=4, optional=True, message=SchemaRestrictionResponse, ) - currency_code = proto.Field( + currency_code: str = proto.Field( proto.STRING, number=5, optional=True, ) - time_zone = proto.Field( + time_zone: str = proto.Field( proto.STRING, number=6, optional=True, ) - empty_reason = proto.Field( + empty_reason: str = proto.Field( proto.STRING, number=7, optional=True, ) - subject_to_thresholding = proto.Field( + subject_to_thresholding: bool = proto.Field( proto.BOOL, number=8, optional=True, @@ -1180,7 +1188,7 @@ class DimensionHeader(proto.Message): The dimension's name. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -1200,11 +1208,11 @@ class MetricHeader(proto.Message): The metric's data type. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - type_ = proto.Field( + type_: "MetricType" = proto.Field( proto.ENUM, number=2, enum="MetricType", @@ -1215,7 +1223,7 @@ class PivotHeader(proto.Message): r"""Dimensions' values in a single pivot. Attributes: - pivot_dimension_headers (Sequence[google.analytics.data_v1beta.types.PivotDimensionHeader]): + pivot_dimension_headers (MutableSequence[google.analytics.data_v1beta.types.PivotDimensionHeader]): The size is the same as the cardinality of the corresponding dimension combinations. row_count (int): @@ -1224,12 +1232,14 @@ class PivotHeader(proto.Message): ``offset`` and ``limit`` are specified in the request. """ - pivot_dimension_headers = proto.RepeatedField( + pivot_dimension_headers: MutableSequence[ + "PivotDimensionHeader" + ] = proto.RepeatedField( proto.MESSAGE, number=1, message="PivotDimensionHeader", ) - row_count = proto.Field( + row_count: int = proto.Field( proto.INT32, number=2, ) @@ -1239,11 +1249,11 @@ class PivotDimensionHeader(proto.Message): r"""Summarizes dimension values from a row for this pivot. Attributes: - dimension_values (Sequence[google.analytics.data_v1beta.types.DimensionValue]): + dimension_values (MutableSequence[google.analytics.data_v1beta.types.DimensionValue]): Values of multiple dimensions in a pivot. """ - dimension_values = proto.RepeatedField( + dimension_values: MutableSequence["DimensionValue"] = proto.RepeatedField( proto.MESSAGE, number=1, message="DimensionValue", @@ -1289,20 +1299,20 @@ class Row(proto.Message): ] Attributes: - dimension_values (Sequence[google.analytics.data_v1beta.types.DimensionValue]): + dimension_values (MutableSequence[google.analytics.data_v1beta.types.DimensionValue]): List of requested dimension values. In a PivotReport, dimension_values are only listed for dimensions included in a pivot. - metric_values (Sequence[google.analytics.data_v1beta.types.MetricValue]): + metric_values (MutableSequence[google.analytics.data_v1beta.types.MetricValue]): List of requested visible metric values. """ - dimension_values = proto.RepeatedField( + dimension_values: MutableSequence["DimensionValue"] = proto.RepeatedField( proto.MESSAGE, number=1, message="DimensionValue", ) - metric_values = proto.RepeatedField( + metric_values: MutableSequence["MetricValue"] = proto.RepeatedField( proto.MESSAGE, number=2, message="MetricValue", @@ -1322,7 +1332,7 @@ class DimensionValue(proto.Message): This field is a member of `oneof`_ ``one_value``. """ - value = proto.Field( + value: str = proto.Field( proto.STRING, number=1, oneof="one_value", @@ -1341,7 +1351,7 @@ class MetricValue(proto.Message): This field is a member of `oneof`_ ``one_value``. """ - value = proto.Field( + value: str = proto.Field( proto.STRING, number=4, oneof="one_value", @@ -1369,12 +1379,12 @@ class NumericValue(proto.Message): This field is a member of `oneof`_ ``one_value``. """ - int64_value = proto.Field( + int64_value: int = proto.Field( proto.INT64, number=1, oneof="one_value", ) - double_value = proto.Field( + double_value: float = proto.Field( proto.DOUBLE, number=2, oneof="one_value", @@ -1428,32 +1438,32 @@ class PropertyQuota(proto.Message): hourly quotas. """ - tokens_per_day = proto.Field( + tokens_per_day: "QuotaStatus" = proto.Field( proto.MESSAGE, number=1, message="QuotaStatus", ) - tokens_per_hour = proto.Field( + tokens_per_hour: "QuotaStatus" = proto.Field( proto.MESSAGE, number=2, message="QuotaStatus", ) - concurrent_requests = proto.Field( + concurrent_requests: "QuotaStatus" = proto.Field( proto.MESSAGE, number=3, message="QuotaStatus", ) - server_errors_per_project_per_hour = proto.Field( + server_errors_per_project_per_hour: "QuotaStatus" = proto.Field( proto.MESSAGE, number=4, message="QuotaStatus", ) - potentially_thresholded_requests_per_hour = proto.Field( + potentially_thresholded_requests_per_hour: "QuotaStatus" = proto.Field( proto.MESSAGE, number=5, message="QuotaStatus", ) - tokens_per_project_per_hour = proto.Field( + tokens_per_project_per_hour: "QuotaStatus" = proto.Field( proto.MESSAGE, number=6, message="QuotaStatus", @@ -1470,11 +1480,11 @@ class QuotaStatus(proto.Message): Quota remaining after this request. """ - consumed = proto.Field( + consumed: int = proto.Field( proto.INT32, number=1, ) - remaining = proto.Field( + remaining: int = proto.Field( proto.INT32, number=2, ) @@ -1494,7 +1504,7 @@ class DimensionMetadata(proto.Message): description (str): Description of how this dimension is used and calculated. - deprecated_api_names (Sequence[str]): + deprecated_api_names (MutableSequence[str]): Still usable but deprecated names for this dimension. If populated, this dimension is available by either ``apiName`` or one of ``deprecatedApiNames`` for a period of time. After @@ -1509,27 +1519,27 @@ class DimensionMetadata(proto.Message): metrics are categorized together. """ - api_name = proto.Field( + api_name: str = proto.Field( proto.STRING, number=1, ) - ui_name = proto.Field( + ui_name: str = proto.Field( proto.STRING, number=2, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=3, ) - deprecated_api_names = proto.RepeatedField( + deprecated_api_names: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=4, ) - custom_definition = proto.Field( + custom_definition: bool = proto.Field( proto.BOOL, number=5, ) - category = proto.Field( + category: str = proto.Field( proto.STRING, number=7, ) @@ -1548,7 +1558,7 @@ class MetricMetadata(proto.Message): description (str): Description of how this metric is used and calculated. - deprecated_api_names (Sequence[str]): + deprecated_api_names (MutableSequence[str]): Still usable but deprecated names for this metric. If populated, this metric is available by either ``apiName`` or one of ``deprecatedApiNames`` for a period of time. After @@ -1564,7 +1574,7 @@ class MetricMetadata(proto.Message): custom_definition (bool): True if the metric is a custom metric for this property. - blocked_reasons (Sequence[google.analytics.data_v1beta.types.MetricMetadata.BlockedReason]): + blocked_reasons (MutableSequence[google.analytics.data_v1beta.types.MetricMetadata.BlockedReason]): If reasons are specified, your access is blocked to this metric for this property. API requests from you to this property for this metric will succeed; however, the report @@ -1586,41 +1596,41 @@ class BlockedReason(proto.Enum): NO_REVENUE_METRICS = 1 NO_COST_METRICS = 2 - api_name = proto.Field( + api_name: str = proto.Field( proto.STRING, number=1, ) - ui_name = proto.Field( + ui_name: str = proto.Field( proto.STRING, number=2, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=3, ) - deprecated_api_names = proto.RepeatedField( + deprecated_api_names: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=4, ) - type_ = proto.Field( + type_: "MetricType" = proto.Field( proto.ENUM, number=5, enum="MetricType", ) - expression = proto.Field( + expression: str = proto.Field( proto.STRING, number=6, ) - custom_definition = proto.Field( + custom_definition: bool = proto.Field( proto.BOOL, number=7, ) - blocked_reasons = proto.RepeatedField( + blocked_reasons: MutableSequence[BlockedReason] = proto.RepeatedField( proto.ENUM, number=8, enum=BlockedReason, ) - category = proto.Field( + category: str = proto.Field( proto.STRING, number=10, ) @@ -1645,13 +1655,13 @@ class DimensionCompatibility(proto.Message): This field is a member of `oneof`_ ``_compatibility``. """ - dimension_metadata = proto.Field( + dimension_metadata: "DimensionMetadata" = proto.Field( proto.MESSAGE, number=1, optional=True, message="DimensionMetadata", ) - compatibility = proto.Field( + compatibility: "Compatibility" = proto.Field( proto.ENUM, number=2, optional=True, @@ -1678,13 +1688,13 @@ class MetricCompatibility(proto.Message): This field is a member of `oneof`_ ``_compatibility``. """ - metric_metadata = proto.Field( + metric_metadata: "MetricMetadata" = proto.Field( proto.MESSAGE, number=1, optional=True, message="MetricMetadata", ) - compatibility = proto.Field( + compatibility: "Compatibility" = proto.Field( proto.ENUM, number=2, optional=True, diff --git a/owl-bot-staging/v1alpha/.coveragerc b/owl-bot-staging/v1alpha/.coveragerc deleted file mode 100644 index 535122d..0000000 --- a/owl-bot-staging/v1alpha/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/analytics/data/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1alpha/.flake8 b/owl-bot-staging/v1alpha/.flake8 deleted file mode 100644 index 29227d4..0000000 --- a/owl-bot-staging/v1alpha/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# 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/v1alpha/MANIFEST.in b/owl-bot-staging/v1alpha/MANIFEST.in deleted file mode 100644 index 938f3f3..0000000 --- a/owl-bot-staging/v1alpha/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/analytics/data *.py -recursive-include google/analytics/data_v1alpha *.py diff --git a/owl-bot-staging/v1alpha/README.rst b/owl-bot-staging/v1alpha/README.rst deleted file mode 100644 index d62497b..0000000 --- a/owl-bot-staging/v1alpha/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Analytics Data 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 Data 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/v1alpha/docs/conf.py b/owl-bot-staging/v1alpha/docs/conf.py deleted file mode 100644 index ad79bba..0000000 --- a/owl-bot-staging/v1alpha/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-data 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-data" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google 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-data-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-data.tex", - u"google-analytics-data 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-data", - u"Google Analytics Data 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-data", - u"google-analytics-data Documentation", - author, - "google-analytics-data", - "GAPIC library for Google Analytics Data 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/v1alpha/docs/data_v1alpha/alpha_analytics_data.rst b/owl-bot-staging/v1alpha/docs/data_v1alpha/alpha_analytics_data.rst deleted file mode 100644 index a59186b..0000000 --- a/owl-bot-staging/v1alpha/docs/data_v1alpha/alpha_analytics_data.rst +++ /dev/null @@ -1,6 +0,0 @@ -AlphaAnalyticsData ------------------------------------- - -.. automodule:: google.analytics.data_v1alpha.services.alpha_analytics_data - :members: - :inherited-members: diff --git a/owl-bot-staging/v1alpha/docs/data_v1alpha/services.rst b/owl-bot-staging/v1alpha/docs/data_v1alpha/services.rst deleted file mode 100644 index 607505d..0000000 --- a/owl-bot-staging/v1alpha/docs/data_v1alpha/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Analytics Data v1alpha API -============================================== -.. toctree:: - :maxdepth: 2 - - alpha_analytics_data diff --git a/owl-bot-staging/v1alpha/docs/data_v1alpha/types.rst b/owl-bot-staging/v1alpha/docs/data_v1alpha/types.rst deleted file mode 100644 index 8498253..0000000 --- a/owl-bot-staging/v1alpha/docs/data_v1alpha/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Analytics Data v1alpha API -=========================================== - -.. automodule:: google.analytics.data_v1alpha.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1alpha/docs/index.rst b/owl-bot-staging/v1alpha/docs/index.rst deleted file mode 100644 index 1eb47c6..0000000 --- a/owl-bot-staging/v1alpha/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - data_v1alpha/services - data_v1alpha/types diff --git a/owl-bot-staging/v1alpha/google/analytics/data/__init__.py b/owl-bot-staging/v1alpha/google/analytics/data/__init__.py deleted file mode 100644 index 6902c35..0000000 --- a/owl-bot-staging/v1alpha/google/analytics/data/__init__.py +++ /dev/null @@ -1,157 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.data import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.analytics.data_v1alpha.services.alpha_analytics_data.client import AlphaAnalyticsDataClient -from google.analytics.data_v1alpha.services.alpha_analytics_data.async_client import AlphaAnalyticsDataAsyncClient - -from google.analytics.data_v1alpha.types.analytics_data_api import RunFunnelReportRequest -from google.analytics.data_v1alpha.types.analytics_data_api import RunFunnelReportResponse -from google.analytics.data_v1alpha.types.data import BetweenFilter -from google.analytics.data_v1alpha.types.data import DateRange -from google.analytics.data_v1alpha.types.data import Dimension -from google.analytics.data_v1alpha.types.data import DimensionExpression -from google.analytics.data_v1alpha.types.data import DimensionHeader -from google.analytics.data_v1alpha.types.data import DimensionValue -from google.analytics.data_v1alpha.types.data import EventSegment -from google.analytics.data_v1alpha.types.data import EventSegmentConditionGroup -from google.analytics.data_v1alpha.types.data import EventSegmentCriteria -from google.analytics.data_v1alpha.types.data import EventSegmentExclusion -from google.analytics.data_v1alpha.types.data import Filter -from google.analytics.data_v1alpha.types.data import FilterExpression -from google.analytics.data_v1alpha.types.data import FilterExpressionList -from google.analytics.data_v1alpha.types.data import Funnel -from google.analytics.data_v1alpha.types.data import FunnelBreakdown -from google.analytics.data_v1alpha.types.data import FunnelEventFilter -from google.analytics.data_v1alpha.types.data import FunnelFieldFilter -from google.analytics.data_v1alpha.types.data import FunnelFilterExpression -from google.analytics.data_v1alpha.types.data import FunnelFilterExpressionList -from google.analytics.data_v1alpha.types.data import FunnelNextAction -from google.analytics.data_v1alpha.types.data import FunnelParameterFilter -from google.analytics.data_v1alpha.types.data import FunnelParameterFilterExpression -from google.analytics.data_v1alpha.types.data import FunnelParameterFilterExpressionList -from google.analytics.data_v1alpha.types.data import FunnelResponseMetadata -from google.analytics.data_v1alpha.types.data import FunnelStep -from google.analytics.data_v1alpha.types.data import FunnelSubReport -from google.analytics.data_v1alpha.types.data import InListFilter -from google.analytics.data_v1alpha.types.data import MetricHeader -from google.analytics.data_v1alpha.types.data import MetricValue -from google.analytics.data_v1alpha.types.data import NumericFilter -from google.analytics.data_v1alpha.types.data import NumericValue -from google.analytics.data_v1alpha.types.data import PropertyQuota -from google.analytics.data_v1alpha.types.data import QuotaStatus -from google.analytics.data_v1alpha.types.data import Row -from google.analytics.data_v1alpha.types.data import SamplingMetadata -from google.analytics.data_v1alpha.types.data import Segment -from google.analytics.data_v1alpha.types.data import SegmentEventFilter -from google.analytics.data_v1alpha.types.data import SegmentFilter -from google.analytics.data_v1alpha.types.data import SegmentFilterExpression -from google.analytics.data_v1alpha.types.data import SegmentFilterExpressionList -from google.analytics.data_v1alpha.types.data import SegmentFilterScoping -from google.analytics.data_v1alpha.types.data import SegmentParameterFilter -from google.analytics.data_v1alpha.types.data import SegmentParameterFilterExpression -from google.analytics.data_v1alpha.types.data import SegmentParameterFilterExpressionList -from google.analytics.data_v1alpha.types.data import SegmentParameterFilterScoping -from google.analytics.data_v1alpha.types.data import SessionSegment -from google.analytics.data_v1alpha.types.data import SessionSegmentConditionGroup -from google.analytics.data_v1alpha.types.data import SessionSegmentCriteria -from google.analytics.data_v1alpha.types.data import SessionSegmentExclusion -from google.analytics.data_v1alpha.types.data import StringFilter -from google.analytics.data_v1alpha.types.data import UserSegment -from google.analytics.data_v1alpha.types.data import UserSegmentConditionGroup -from google.analytics.data_v1alpha.types.data import UserSegmentCriteria -from google.analytics.data_v1alpha.types.data import UserSegmentExclusion -from google.analytics.data_v1alpha.types.data import UserSegmentSequenceGroup -from google.analytics.data_v1alpha.types.data import UserSequenceStep -from google.analytics.data_v1alpha.types.data import EventCriteriaScoping -from google.analytics.data_v1alpha.types.data import EventExclusionDuration -from google.analytics.data_v1alpha.types.data import MetricType -from google.analytics.data_v1alpha.types.data import SessionCriteriaScoping -from google.analytics.data_v1alpha.types.data import SessionExclusionDuration -from google.analytics.data_v1alpha.types.data import UserCriteriaScoping -from google.analytics.data_v1alpha.types.data import UserExclusionDuration - -__all__ = ('AlphaAnalyticsDataClient', - 'AlphaAnalyticsDataAsyncClient', - 'RunFunnelReportRequest', - 'RunFunnelReportResponse', - 'BetweenFilter', - 'DateRange', - 'Dimension', - 'DimensionExpression', - 'DimensionHeader', - 'DimensionValue', - 'EventSegment', - 'EventSegmentConditionGroup', - 'EventSegmentCriteria', - 'EventSegmentExclusion', - 'Filter', - 'FilterExpression', - 'FilterExpressionList', - 'Funnel', - 'FunnelBreakdown', - 'FunnelEventFilter', - 'FunnelFieldFilter', - 'FunnelFilterExpression', - 'FunnelFilterExpressionList', - 'FunnelNextAction', - 'FunnelParameterFilter', - 'FunnelParameterFilterExpression', - 'FunnelParameterFilterExpressionList', - 'FunnelResponseMetadata', - 'FunnelStep', - 'FunnelSubReport', - 'InListFilter', - 'MetricHeader', - 'MetricValue', - 'NumericFilter', - 'NumericValue', - 'PropertyQuota', - 'QuotaStatus', - 'Row', - 'SamplingMetadata', - 'Segment', - 'SegmentEventFilter', - 'SegmentFilter', - 'SegmentFilterExpression', - 'SegmentFilterExpressionList', - 'SegmentFilterScoping', - 'SegmentParameterFilter', - 'SegmentParameterFilterExpression', - 'SegmentParameterFilterExpressionList', - 'SegmentParameterFilterScoping', - 'SessionSegment', - 'SessionSegmentConditionGroup', - 'SessionSegmentCriteria', - 'SessionSegmentExclusion', - 'StringFilter', - 'UserSegment', - 'UserSegmentConditionGroup', - 'UserSegmentCriteria', - 'UserSegmentExclusion', - 'UserSegmentSequenceGroup', - 'UserSequenceStep', - 'EventCriteriaScoping', - 'EventExclusionDuration', - 'MetricType', - 'SessionCriteriaScoping', - 'SessionExclusionDuration', - 'UserCriteriaScoping', - 'UserExclusionDuration', -) diff --git a/owl-bot-staging/v1alpha/google/analytics/data/gapic_version.py b/owl-bot-staging/v1alpha/google/analytics/data/gapic_version.py deleted file mode 100644 index 35859c3..0000000 --- a/owl-bot-staging/v1alpha/google/analytics/data/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.1.0" diff --git a/owl-bot-staging/v1alpha/google/analytics/data/py.typed b/owl-bot-staging/v1alpha/google/analytics/data/py.typed deleted file mode 100644 index 1d549e5..0000000 --- a/owl-bot-staging/v1alpha/google/analytics/data/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-analytics-data package uses inline types. diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/__init__.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/__init__.py deleted file mode 100644 index a6fd5d7..0000000 --- a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/__init__.py +++ /dev/null @@ -1,158 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.data import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.alpha_analytics_data import AlphaAnalyticsDataClient -from .services.alpha_analytics_data import AlphaAnalyticsDataAsyncClient - -from .types.analytics_data_api import RunFunnelReportRequest -from .types.analytics_data_api import RunFunnelReportResponse -from .types.data import BetweenFilter -from .types.data import DateRange -from .types.data import Dimension -from .types.data import DimensionExpression -from .types.data import DimensionHeader -from .types.data import DimensionValue -from .types.data import EventSegment -from .types.data import EventSegmentConditionGroup -from .types.data import EventSegmentCriteria -from .types.data import EventSegmentExclusion -from .types.data import Filter -from .types.data import FilterExpression -from .types.data import FilterExpressionList -from .types.data import Funnel -from .types.data import FunnelBreakdown -from .types.data import FunnelEventFilter -from .types.data import FunnelFieldFilter -from .types.data import FunnelFilterExpression -from .types.data import FunnelFilterExpressionList -from .types.data import FunnelNextAction -from .types.data import FunnelParameterFilter -from .types.data import FunnelParameterFilterExpression -from .types.data import FunnelParameterFilterExpressionList -from .types.data import FunnelResponseMetadata -from .types.data import FunnelStep -from .types.data import FunnelSubReport -from .types.data import InListFilter -from .types.data import MetricHeader -from .types.data import MetricValue -from .types.data import NumericFilter -from .types.data import NumericValue -from .types.data import PropertyQuota -from .types.data import QuotaStatus -from .types.data import Row -from .types.data import SamplingMetadata -from .types.data import Segment -from .types.data import SegmentEventFilter -from .types.data import SegmentFilter -from .types.data import SegmentFilterExpression -from .types.data import SegmentFilterExpressionList -from .types.data import SegmentFilterScoping -from .types.data import SegmentParameterFilter -from .types.data import SegmentParameterFilterExpression -from .types.data import SegmentParameterFilterExpressionList -from .types.data import SegmentParameterFilterScoping -from .types.data import SessionSegment -from .types.data import SessionSegmentConditionGroup -from .types.data import SessionSegmentCriteria -from .types.data import SessionSegmentExclusion -from .types.data import StringFilter -from .types.data import UserSegment -from .types.data import UserSegmentConditionGroup -from .types.data import UserSegmentCriteria -from .types.data import UserSegmentExclusion -from .types.data import UserSegmentSequenceGroup -from .types.data import UserSequenceStep -from .types.data import EventCriteriaScoping -from .types.data import EventExclusionDuration -from .types.data import MetricType -from .types.data import SessionCriteriaScoping -from .types.data import SessionExclusionDuration -from .types.data import UserCriteriaScoping -from .types.data import UserExclusionDuration - -__all__ = ( - 'AlphaAnalyticsDataAsyncClient', -'AlphaAnalyticsDataClient', -'BetweenFilter', -'DateRange', -'Dimension', -'DimensionExpression', -'DimensionHeader', -'DimensionValue', -'EventCriteriaScoping', -'EventExclusionDuration', -'EventSegment', -'EventSegmentConditionGroup', -'EventSegmentCriteria', -'EventSegmentExclusion', -'Filter', -'FilterExpression', -'FilterExpressionList', -'Funnel', -'FunnelBreakdown', -'FunnelEventFilter', -'FunnelFieldFilter', -'FunnelFilterExpression', -'FunnelFilterExpressionList', -'FunnelNextAction', -'FunnelParameterFilter', -'FunnelParameterFilterExpression', -'FunnelParameterFilterExpressionList', -'FunnelResponseMetadata', -'FunnelStep', -'FunnelSubReport', -'InListFilter', -'MetricHeader', -'MetricType', -'MetricValue', -'NumericFilter', -'NumericValue', -'PropertyQuota', -'QuotaStatus', -'Row', -'RunFunnelReportRequest', -'RunFunnelReportResponse', -'SamplingMetadata', -'Segment', -'SegmentEventFilter', -'SegmentFilter', -'SegmentFilterExpression', -'SegmentFilterExpressionList', -'SegmentFilterScoping', -'SegmentParameterFilter', -'SegmentParameterFilterExpression', -'SegmentParameterFilterExpressionList', -'SegmentParameterFilterScoping', -'SessionCriteriaScoping', -'SessionExclusionDuration', -'SessionSegment', -'SessionSegmentConditionGroup', -'SessionSegmentCriteria', -'SessionSegmentExclusion', -'StringFilter', -'UserCriteriaScoping', -'UserExclusionDuration', -'UserSegment', -'UserSegmentConditionGroup', -'UserSegmentCriteria', -'UserSegmentExclusion', -'UserSegmentSequenceGroup', -'UserSequenceStep', -) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/gapic_metadata.json b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/gapic_metadata.json deleted file mode 100644 index f8812c5..0000000 --- a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/gapic_metadata.json +++ /dev/null @@ -1,43 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.analytics.data_v1alpha", - "protoPackage": "google.analytics.data.v1alpha", - "schema": "1.0", - "services": { - "AlphaAnalyticsData": { - "clients": { - "grpc": { - "libraryClient": "AlphaAnalyticsDataClient", - "rpcs": { - "RunFunnelReport": { - "methods": [ - "run_funnel_report" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AlphaAnalyticsDataAsyncClient", - "rpcs": { - "RunFunnelReport": { - "methods": [ - "run_funnel_report" - ] - } - } - }, - "rest": { - "libraryClient": "AlphaAnalyticsDataClient", - "rpcs": { - "RunFunnelReport": { - "methods": [ - "run_funnel_report" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/py.typed b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/py.typed deleted file mode 100644 index 1d549e5..0000000 --- a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-analytics-data package uses inline types. diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/__init__.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/__init__.py deleted file mode 100644 index e8e1c38..0000000 --- a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/__init__.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/__init__.py deleted file mode 100644 index 8948d2f..0000000 --- a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 AlphaAnalyticsDataClient -from .async_client import AlphaAnalyticsDataAsyncClient - -__all__ = ( - 'AlphaAnalyticsDataClient', - 'AlphaAnalyticsDataAsyncClient', -) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/async_client.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/async_client.py deleted file mode 100644 index a8eaaaf..0000000 --- a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/async_client.py +++ /dev/null @@ -1,294 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.analytics.data_v1alpha.types import analytics_data_api -from google.analytics.data_v1alpha.types import data -from .transports.base import AlphaAnalyticsDataTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AlphaAnalyticsDataGrpcAsyncIOTransport -from .client import AlphaAnalyticsDataClient - - -class AlphaAnalyticsDataAsyncClient: - """Google Analytics reporting data service.""" - - _client: AlphaAnalyticsDataClient - - DEFAULT_ENDPOINT = AlphaAnalyticsDataClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AlphaAnalyticsDataClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(AlphaAnalyticsDataClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AlphaAnalyticsDataClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AlphaAnalyticsDataClient.common_folder_path) - parse_common_folder_path = staticmethod(AlphaAnalyticsDataClient.parse_common_folder_path) - common_organization_path = staticmethod(AlphaAnalyticsDataClient.common_organization_path) - parse_common_organization_path = staticmethod(AlphaAnalyticsDataClient.parse_common_organization_path) - common_project_path = staticmethod(AlphaAnalyticsDataClient.common_project_path) - parse_common_project_path = staticmethod(AlphaAnalyticsDataClient.parse_common_project_path) - common_location_path = staticmethod(AlphaAnalyticsDataClient.common_location_path) - parse_common_location_path = staticmethod(AlphaAnalyticsDataClient.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: - AlphaAnalyticsDataAsyncClient: The constructed client. - """ - return AlphaAnalyticsDataClient.from_service_account_info.__func__(AlphaAnalyticsDataAsyncClient, 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: - AlphaAnalyticsDataAsyncClient: The constructed client. - """ - return AlphaAnalyticsDataClient.from_service_account_file.__func__(AlphaAnalyticsDataAsyncClient, 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 variabel 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 AlphaAnalyticsDataClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AlphaAnalyticsDataTransport: - """Returns the transport used by the client instance. - - Returns: - AlphaAnalyticsDataTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(AlphaAnalyticsDataClient).get_transport_class, type(AlphaAnalyticsDataClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AlphaAnalyticsDataTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the alpha analytics data client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.AlphaAnalyticsDataTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = AlphaAnalyticsDataClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def run_funnel_report(self, - request: Optional[Union[analytics_data_api.RunFunnelReportRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.RunFunnelReportResponse: - r"""Returns a customized funnel report of your Google Analytics - event data. The data returned from the API is as a table with - columns for the requested dimensions and metrics. - - Funnel exploration lets you visualize the steps your users take - to complete a task and quickly see how well they are succeeding - or failing at each step. For example, how do prospects become - shoppers and then become buyers? How do one time buyers become - repeat buyers? With this information, you can improve - inefficient or abandoned customer journeys. To learn more, see - `GA4 Funnel - Explorations `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 data_v1alpha - - async def sample_run_funnel_report(): - # Create a client - client = data_v1alpha.AlphaAnalyticsDataAsyncClient() - - # Initialize request argument(s) - request = data_v1alpha.RunFunnelReportRequest( - ) - - # Make the request - response = await client.run_funnel_report(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.analytics.data_v1alpha.types.RunFunnelReportRequest, dict]]): - The request object. The request for a funnel 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.data_v1alpha.types.RunFunnelReportResponse: - The funnel report response contains - two sub reports. The two sub reports are - different combinations of dimensions and - metrics. - - """ - # Create or coerce a protobuf request object. - request = analytics_data_api.RunFunnelReportRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.run_funnel_report, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("property", request.property), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-analytics-data", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "AlphaAnalyticsDataAsyncClient", -) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py deleted file mode 100644 index a135a8a..0000000 --- a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py +++ /dev/null @@ -1,492 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.analytics.data_v1alpha.types import analytics_data_api -from google.analytics.data_v1alpha.types import data -from .transports.base import AlphaAnalyticsDataTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AlphaAnalyticsDataGrpcTransport -from .transports.grpc_asyncio import AlphaAnalyticsDataGrpcAsyncIOTransport -from .transports.rest import AlphaAnalyticsDataRestTransport - - -class AlphaAnalyticsDataClientMeta(type): - """Metaclass for the AlphaAnalyticsData 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[AlphaAnalyticsDataTransport]] - _transport_registry["grpc"] = AlphaAnalyticsDataGrpcTransport - _transport_registry["grpc_asyncio"] = AlphaAnalyticsDataGrpcAsyncIOTransport - _transport_registry["rest"] = AlphaAnalyticsDataRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AlphaAnalyticsDataTransport]: - """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 AlphaAnalyticsDataClient(metaclass=AlphaAnalyticsDataClientMeta): - """Google Analytics reporting data service.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "analyticsdata.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - AlphaAnalyticsDataClient: 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: - AlphaAnalyticsDataClient: 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) -> AlphaAnalyticsDataTransport: - """Returns the transport used by the client instance. - - Returns: - AlphaAnalyticsDataTransport: The transport used by the client - instance. - """ - return self._transport - - @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): - """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 variabel 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. - """ - 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 - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AlphaAnalyticsDataTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the alpha analytics data client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, AlphaAnalyticsDataTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - NOTE: "rest" transport functionality is currently in a - beta state (preview). We welcome your feedback via an - issue in this library's source repository. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(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. - if isinstance(transport, AlphaAnalyticsDataTransport): - # transport is a AlphaAnalyticsDataTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def run_funnel_report(self, - request: Optional[Union[analytics_data_api.RunFunnelReportRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.RunFunnelReportResponse: - r"""Returns a customized funnel report of your Google Analytics - event data. The data returned from the API is as a table with - columns for the requested dimensions and metrics. - - Funnel exploration lets you visualize the steps your users take - to complete a task and quickly see how well they are succeeding - or failing at each step. For example, how do prospects become - shoppers and then become buyers? How do one time buyers become - repeat buyers? With this information, you can improve - inefficient or abandoned customer journeys. To learn more, see - `GA4 Funnel - Explorations `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 data_v1alpha - - def sample_run_funnel_report(): - # Create a client - client = data_v1alpha.AlphaAnalyticsDataClient() - - # Initialize request argument(s) - request = data_v1alpha.RunFunnelReportRequest( - ) - - # Make the request - response = client.run_funnel_report(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.analytics.data_v1alpha.types.RunFunnelReportRequest, dict]): - The request object. The request for a funnel 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.data_v1alpha.types.RunFunnelReportResponse: - The funnel report response contains - two sub reports. The two sub reports are - different combinations of dimensions and - metrics. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a analytics_data_api.RunFunnelReportRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, analytics_data_api.RunFunnelReportRequest): - request = analytics_data_api.RunFunnelReportRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.run_funnel_report] - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-analytics-data", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "AlphaAnalyticsDataClient", -) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/__init__.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/__init__.py deleted file mode 100644 index 45c2709..0000000 --- a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 AlphaAnalyticsDataTransport -from .grpc import AlphaAnalyticsDataGrpcTransport -from .grpc_asyncio import AlphaAnalyticsDataGrpcAsyncIOTransport -from .rest import AlphaAnalyticsDataRestTransport -from .rest import AlphaAnalyticsDataRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AlphaAnalyticsDataTransport]] -_transport_registry['grpc'] = AlphaAnalyticsDataGrpcTransport -_transport_registry['grpc_asyncio'] = AlphaAnalyticsDataGrpcAsyncIOTransport -_transport_registry['rest'] = AlphaAnalyticsDataRestTransport - -__all__ = ( - 'AlphaAnalyticsDataTransport', - 'AlphaAnalyticsDataGrpcTransport', - 'AlphaAnalyticsDataGrpcAsyncIOTransport', - 'AlphaAnalyticsDataRestTransport', - 'AlphaAnalyticsDataRestInterceptor', -) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/base.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/base.py deleted file mode 100644 index 0b338c5..0000000 --- a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/base.py +++ /dev/null @@ -1,155 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.analytics.data_v1alpha.types import analytics_data_api - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-analytics-data', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class AlphaAnalyticsDataTransport(abc.ABC): - """Abstract transport class for AlphaAnalyticsData.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/analytics', - 'https://www.googleapis.com/auth/analytics.readonly', - ) - - DEFAULT_HOST: str = 'analyticsdata.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. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.run_funnel_report: gapic_v1.method.wrap_method( - self.run_funnel_report, - default_timeout=60.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def run_funnel_report(self) -> Callable[ - [analytics_data_api.RunFunnelReportRequest], - Union[ - analytics_data_api.RunFunnelReportResponse, - Awaitable[analytics_data_api.RunFunnelReportResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AlphaAnalyticsDataTransport', -) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc.py deleted file mode 100644 index 1f2de5b..0000000 --- a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc.py +++ /dev/null @@ -1,275 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.data_v1alpha.types import analytics_data_api -from .base import AlphaAnalyticsDataTransport, DEFAULT_CLIENT_INFO - - -class AlphaAnalyticsDataGrpcTransport(AlphaAnalyticsDataTransport): - """gRPC backend transport for AlphaAnalyticsData. - - Google Analytics reporting data service. - - 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 = 'analyticsdata.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'analyticsdata.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 run_funnel_report(self) -> Callable[ - [analytics_data_api.RunFunnelReportRequest], - analytics_data_api.RunFunnelReportResponse]: - r"""Return a callable for the run funnel report method over gRPC. - - Returns a customized funnel report of your Google Analytics - event data. The data returned from the API is as a table with - columns for the requested dimensions and metrics. - - Funnel exploration lets you visualize the steps your users take - to complete a task and quickly see how well they are succeeding - or failing at each step. For example, how do prospects become - shoppers and then become buyers? How do one time buyers become - repeat buyers? With this information, you can improve - inefficient or abandoned customer journeys. To learn more, see - `GA4 Funnel - Explorations `__. - - Returns: - Callable[[~.RunFunnelReportRequest], - ~.RunFunnelReportResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_funnel_report' not in self._stubs: - self._stubs['run_funnel_report'] = self.grpc_channel.unary_unary( - '/google.analytics.data.v1alpha.AlphaAnalyticsData/RunFunnelReport', - request_serializer=analytics_data_api.RunFunnelReportRequest.serialize, - response_deserializer=analytics_data_api.RunFunnelReportResponse.deserialize, - ) - return self._stubs['run_funnel_report'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AlphaAnalyticsDataGrpcTransport', -) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py deleted file mode 100644 index b9a934e..0000000 --- a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py +++ /dev/null @@ -1,274 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.analytics.data_v1alpha.types import analytics_data_api -from .base import AlphaAnalyticsDataTransport, DEFAULT_CLIENT_INFO -from .grpc import AlphaAnalyticsDataGrpcTransport - - -class AlphaAnalyticsDataGrpcAsyncIOTransport(AlphaAnalyticsDataTransport): - """gRPC AsyncIO backend transport for AlphaAnalyticsData. - - Google Analytics reporting data service. - - 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 = 'analyticsdata.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'analyticsdata.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def run_funnel_report(self) -> Callable[ - [analytics_data_api.RunFunnelReportRequest], - Awaitable[analytics_data_api.RunFunnelReportResponse]]: - r"""Return a callable for the run funnel report method over gRPC. - - Returns a customized funnel report of your Google Analytics - event data. The data returned from the API is as a table with - columns for the requested dimensions and metrics. - - Funnel exploration lets you visualize the steps your users take - to complete a task and quickly see how well they are succeeding - or failing at each step. For example, how do prospects become - shoppers and then become buyers? How do one time buyers become - repeat buyers? With this information, you can improve - inefficient or abandoned customer journeys. To learn more, see - `GA4 Funnel - Explorations `__. - - Returns: - Callable[[~.RunFunnelReportRequest], - Awaitable[~.RunFunnelReportResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_funnel_report' not in self._stubs: - self._stubs['run_funnel_report'] = self.grpc_channel.unary_unary( - '/google.analytics.data.v1alpha.AlphaAnalyticsData/RunFunnelReport', - request_serializer=analytics_data_api.RunFunnelReportRequest.serialize, - response_deserializer=analytics_data_api.RunFunnelReportResponse.deserialize, - ) - return self._stubs['run_funnel_report'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'AlphaAnalyticsDataGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest.py deleted file mode 100644 index 6356b25..0000000 --- a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest.py +++ /dev/null @@ -1,297 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.analytics.data_v1alpha.types import analytics_data_api - -from .base import AlphaAnalyticsDataTransport, 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 AlphaAnalyticsDataRestInterceptor: - """Interceptor for AlphaAnalyticsData. - - 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 AlphaAnalyticsDataRestTransport. - - .. code-block:: python - class MyCustomAlphaAnalyticsDataInterceptor(AlphaAnalyticsDataRestInterceptor): - def pre_run_funnel_report(request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_run_funnel_report(response): - logging.log(f"Received response: {response}") - - transport = AlphaAnalyticsDataRestTransport(interceptor=MyCustomAlphaAnalyticsDataInterceptor()) - client = AlphaAnalyticsDataClient(transport=transport) - - - """ - def pre_run_funnel_report(self, request: analytics_data_api.RunFunnelReportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_data_api.RunFunnelReportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for run_funnel_report - - Override in a subclass to manipulate the request or metadata - before they are sent to the AlphaAnalyticsData server. - """ - return request, metadata - - def post_run_funnel_report(self, response: analytics_data_api.RunFunnelReportResponse) -> analytics_data_api.RunFunnelReportResponse: - """Post-rpc interceptor for run_funnel_report - - Override in a subclass to manipulate the response - after it is returned by the AlphaAnalyticsData server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class AlphaAnalyticsDataRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AlphaAnalyticsDataRestInterceptor - - -class AlphaAnalyticsDataRestTransport(AlphaAnalyticsDataTransport): - """REST backend transport for AlphaAnalyticsData. - - Google Analytics reporting data service. - - 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 - - NOTE: This REST transport functionality is currently in a beta - state (preview). We welcome your feedback via an issue in this - library's source repository. Thank you! - """ - - def __init__(self, *, - host: str = 'analyticsdata.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[AlphaAnalyticsDataRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - NOTE: This REST transport functionality is currently in a beta - state (preview). We welcome your feedback via a GitHub issue in - this library's repository. Thank you! - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is 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 AlphaAnalyticsDataRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _RunFunnelReport(AlphaAnalyticsDataRestStub): - def __hash__(self): - return hash("RunFunnelReport") - - def __call__(self, - request: analytics_data_api.RunFunnelReportRequest, *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.RunFunnelReportResponse: - r"""Call the run funnel report method over HTTP. - - Args: - request (~.analytics_data_api.RunFunnelReportRequest): - The request object. The request for a funnel 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_data_api.RunFunnelReportResponse: - The funnel report response contains - two sub reports. The two sub reports are - different combinations of dimensions and - metrics. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha/{property=properties/*}:runFunnelReport', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_run_funnel_report(request, metadata) - pb_request = analytics_data_api.RunFunnelReportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=False - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=False, - )) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._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_data_api.RunFunnelReportResponse() - pb_resp = analytics_data_api.RunFunnelReportResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_run_funnel_report(resp) - return resp - - @property - def run_funnel_report(self) -> Callable[ - [analytics_data_api.RunFunnelReportRequest], - analytics_data_api.RunFunnelReportResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._RunFunnelReport(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AlphaAnalyticsDataRestTransport', -) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/__init__.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/__init__.py deleted file mode 100644 index 0634c97..0000000 --- a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/__init__.py +++ /dev/null @@ -1,152 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .analytics_data_api import ( - RunFunnelReportRequest, - RunFunnelReportResponse, -) -from .data import ( - BetweenFilter, - DateRange, - Dimension, - DimensionExpression, - DimensionHeader, - DimensionValue, - EventSegment, - EventSegmentConditionGroup, - EventSegmentCriteria, - EventSegmentExclusion, - Filter, - FilterExpression, - FilterExpressionList, - Funnel, - FunnelBreakdown, - FunnelEventFilter, - FunnelFieldFilter, - FunnelFilterExpression, - FunnelFilterExpressionList, - FunnelNextAction, - FunnelParameterFilter, - FunnelParameterFilterExpression, - FunnelParameterFilterExpressionList, - FunnelResponseMetadata, - FunnelStep, - FunnelSubReport, - InListFilter, - MetricHeader, - MetricValue, - NumericFilter, - NumericValue, - PropertyQuota, - QuotaStatus, - Row, - SamplingMetadata, - Segment, - SegmentEventFilter, - SegmentFilter, - SegmentFilterExpression, - SegmentFilterExpressionList, - SegmentFilterScoping, - SegmentParameterFilter, - SegmentParameterFilterExpression, - SegmentParameterFilterExpressionList, - SegmentParameterFilterScoping, - SessionSegment, - SessionSegmentConditionGroup, - SessionSegmentCriteria, - SessionSegmentExclusion, - StringFilter, - UserSegment, - UserSegmentConditionGroup, - UserSegmentCriteria, - UserSegmentExclusion, - UserSegmentSequenceGroup, - UserSequenceStep, - EventCriteriaScoping, - EventExclusionDuration, - MetricType, - SessionCriteriaScoping, - SessionExclusionDuration, - UserCriteriaScoping, - UserExclusionDuration, -) - -__all__ = ( - 'RunFunnelReportRequest', - 'RunFunnelReportResponse', - 'BetweenFilter', - 'DateRange', - 'Dimension', - 'DimensionExpression', - 'DimensionHeader', - 'DimensionValue', - 'EventSegment', - 'EventSegmentConditionGroup', - 'EventSegmentCriteria', - 'EventSegmentExclusion', - 'Filter', - 'FilterExpression', - 'FilterExpressionList', - 'Funnel', - 'FunnelBreakdown', - 'FunnelEventFilter', - 'FunnelFieldFilter', - 'FunnelFilterExpression', - 'FunnelFilterExpressionList', - 'FunnelNextAction', - 'FunnelParameterFilter', - 'FunnelParameterFilterExpression', - 'FunnelParameterFilterExpressionList', - 'FunnelResponseMetadata', - 'FunnelStep', - 'FunnelSubReport', - 'InListFilter', - 'MetricHeader', - 'MetricValue', - 'NumericFilter', - 'NumericValue', - 'PropertyQuota', - 'QuotaStatus', - 'Row', - 'SamplingMetadata', - 'Segment', - 'SegmentEventFilter', - 'SegmentFilter', - 'SegmentFilterExpression', - 'SegmentFilterExpressionList', - 'SegmentFilterScoping', - 'SegmentParameterFilter', - 'SegmentParameterFilterExpression', - 'SegmentParameterFilterExpressionList', - 'SegmentParameterFilterScoping', - 'SessionSegment', - 'SessionSegmentConditionGroup', - 'SessionSegmentCriteria', - 'SessionSegmentExclusion', - 'StringFilter', - 'UserSegment', - 'UserSegmentConditionGroup', - 'UserSegmentCriteria', - 'UserSegmentExclusion', - 'UserSegmentSequenceGroup', - 'UserSequenceStep', - 'EventCriteriaScoping', - 'EventExclusionDuration', - 'MetricType', - 'SessionCriteriaScoping', - 'SessionExclusionDuration', - 'UserCriteriaScoping', - 'UserExclusionDuration', -) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/analytics_data_api.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/analytics_data_api.py deleted file mode 100644 index 776fbf7..0000000 --- a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/analytics_data_api.py +++ /dev/null @@ -1,220 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.analytics.data_v1alpha.types import data - - -__protobuf__ = proto.module( - package='google.analytics.data.v1alpha', - manifest={ - 'RunFunnelReportRequest', - 'RunFunnelReportResponse', - }, -) - - -class RunFunnelReportRequest(proto.Message): - r"""The request for a funnel report. - - Attributes: - property (str): - A Google Analytics GA4 property identifier whose events are - tracked. Specified in the URL path and not the body. To - learn more, see `where to find your Property - ID `__. - Within a batch request, this property should either be - unspecified or consistent with the batch-level property. - - Example: properties/1234 - date_ranges (MutableSequence[google.analytics.data_v1alpha.types.DateRange]): - Date ranges of data 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 event data for the - overlapping days is included in the response - rows for both date ranges. - funnel (google.analytics.data_v1alpha.types.Funnel): - The configuration of this request's funnel. - This funnel configuration is required. - funnel_breakdown (google.analytics.data_v1alpha.types.FunnelBreakdown): - If specified, this breakdown adds a dimension to the funnel - table sub report response. This breakdown dimension expands - each funnel step to the unique values of the breakdown - dimension. For example, a breakdown by the - ``deviceCategory`` dimension will create rows for - ``mobile``, ``tablet``, ``desktop``, and the total. - funnel_next_action (google.analytics.data_v1alpha.types.FunnelNextAction): - If specified, next action adds a dimension to the funnel - visualization sub report response. This next action - dimension expands each funnel step to the unique values of - the next action. For example a next action of the - ``eventName`` dimension will create rows for several events - (i.e. ``session_start`` & ``click``) and the total. - - Next action only supports ``eventName`` and most Page / - Screen dimensions like ``pageTitle`` and ``pagePath``. - funnel_visualization_type (google.analytics.data_v1alpha.types.RunFunnelReportRequest.FunnelVisualizationType): - The funnel visualization type controls the dimensions - present in the funnel visualization sub report response. If - not specified, ``STANDARD_FUNNEL`` is used. - segments (MutableSequence[google.analytics.data_v1alpha.types.Segment]): - The configurations of segments. Segments are - subsets of a property's data. In a funnel report - with segments, the funnel is evaluated in each - segment. - Each segment specified in this request - produces a separate row in the response; in the - response, each segment identified by its name. - - The segments parameter is optional. Requests are - limited to 4 segments. - 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 can also return fewer rows than the requested - ``limit``, if there aren't as many dimension values as the - ``limit``. - dimension_filter (google.analytics.data_v1alpha.types.FilterExpression): - Dimension filters allow you to ask for only specific - dimension values in the report. To learn more, see `Creating - a Report: Dimension - Filters `__ - for examples. Metrics cannot be used in this filter. - return_property_quota (bool): - Toggles whether to return the current state of this - Analytics Property's quota. Quota is returned in - `PropertyQuota <#PropertyQuota>`__. - """ - class FunnelVisualizationType(proto.Enum): - r"""Controls the dimensions present in the funnel visualization - sub report response. - """ - FUNNEL_VISUALIZATION_TYPE_UNSPECIFIED = 0 - STANDARD_FUNNEL = 1 - TRENDED_FUNNEL = 2 - - property: str = proto.Field( - proto.STRING, - number=1, - ) - date_ranges: MutableSequence[data.DateRange] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=data.DateRange, - ) - funnel: data.Funnel = proto.Field( - proto.MESSAGE, - number=3, - message=data.Funnel, - ) - funnel_breakdown: data.FunnelBreakdown = proto.Field( - proto.MESSAGE, - number=4, - message=data.FunnelBreakdown, - ) - funnel_next_action: data.FunnelNextAction = proto.Field( - proto.MESSAGE, - number=5, - message=data.FunnelNextAction, - ) - funnel_visualization_type: FunnelVisualizationType = proto.Field( - proto.ENUM, - number=6, - enum=FunnelVisualizationType, - ) - segments: MutableSequence[data.Segment] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=data.Segment, - ) - limit: int = proto.Field( - proto.INT64, - number=9, - ) - dimension_filter: data.FilterExpression = proto.Field( - proto.MESSAGE, - number=10, - message=data.FilterExpression, - ) - return_property_quota: bool = proto.Field( - proto.BOOL, - number=12, - ) - - -class RunFunnelReportResponse(proto.Message): - r"""The funnel report response contains two sub reports. The two - sub reports are different combinations of dimensions and - metrics. - - Attributes: - funnel_table (google.analytics.data_v1alpha.types.FunnelSubReport): - The funnel table is a report with the funnel - step, segment, breakdown dimension, active - users, completion rate, abandonments, and - abandonments rate. - - The segment dimension is only present in this - response if a segment was requested. The - breakdown dimension is only present in this - response if it was requested. - funnel_visualization (google.analytics.data_v1alpha.types.FunnelSubReport): - The funnel visualization is a report with the funnel step, - segment, date, next action dimension, and active users. - - The segment dimension is only present in this response if a - segment was requested. The date dimension is only present in - this response if it was requested via the ``TRENDED_FUNNEL`` - funnel type. The next action dimension is only present in - the response if it was requested. - property_quota (google.analytics.data_v1alpha.types.PropertyQuota): - This Analytics Property's quota state - including this request. - kind (str): - Identifies what kind of resource this message is. This - ``kind`` is always the fixed string - "analyticsData#runFunnelReport". Useful to distinguish - between response types in JSON. - """ - - funnel_table: data.FunnelSubReport = proto.Field( - proto.MESSAGE, - number=1, - message=data.FunnelSubReport, - ) - funnel_visualization: data.FunnelSubReport = proto.Field( - proto.MESSAGE, - number=2, - message=data.FunnelSubReport, - ) - property_quota: data.PropertyQuota = proto.Field( - proto.MESSAGE, - number=3, - message=data.PropertyQuota, - ) - kind: str = proto.Field( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/data.py b/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/data.py deleted file mode 100644 index f16beae..0000000 --- a/owl-bot-staging/v1alpha/google/analytics/data_v1alpha/types/data.py +++ /dev/null @@ -1,2404 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.analytics.data.v1alpha', - manifest={ - 'UserCriteriaScoping', - 'UserExclusionDuration', - 'SessionCriteriaScoping', - 'SessionExclusionDuration', - 'EventCriteriaScoping', - 'EventExclusionDuration', - 'MetricType', - 'DateRange', - 'Dimension', - 'DimensionExpression', - 'FilterExpression', - 'FilterExpressionList', - 'Filter', - 'StringFilter', - 'InListFilter', - 'NumericFilter', - 'BetweenFilter', - 'NumericValue', - 'DimensionHeader', - 'MetricHeader', - 'Row', - 'DimensionValue', - 'MetricValue', - 'PropertyQuota', - 'QuotaStatus', - 'FunnelBreakdown', - 'FunnelNextAction', - 'Funnel', - 'FunnelStep', - 'FunnelSubReport', - 'UserSegment', - 'UserSegmentCriteria', - 'UserSegmentConditionGroup', - 'UserSegmentSequenceGroup', - 'UserSequenceStep', - 'UserSegmentExclusion', - 'SessionSegment', - 'SessionSegmentCriteria', - 'SessionSegmentConditionGroup', - 'SessionSegmentExclusion', - 'EventSegment', - 'EventSegmentCriteria', - 'EventSegmentConditionGroup', - 'EventSegmentExclusion', - 'Segment', - 'SegmentFilterExpression', - 'SegmentFilterExpressionList', - 'SegmentFilter', - 'SegmentFilterScoping', - 'SegmentEventFilter', - 'SegmentParameterFilterExpression', - 'SegmentParameterFilterExpressionList', - 'SegmentParameterFilter', - 'SegmentParameterFilterScoping', - 'FunnelFilterExpression', - 'FunnelFilterExpressionList', - 'FunnelFieldFilter', - 'FunnelEventFilter', - 'FunnelParameterFilterExpression', - 'FunnelParameterFilterExpressionList', - 'FunnelParameterFilter', - 'FunnelResponseMetadata', - 'SamplingMetadata', - }, -) - - -class UserCriteriaScoping(proto.Enum): - r"""Scoping specifies which events are considered when evaluating - if a user meets a criteria. - """ - USER_CRITERIA_SCOPING_UNSPECIFIED = 0 - USER_CRITERIA_WITHIN_SAME_EVENT = 1 - USER_CRITERIA_WITHIN_SAME_SESSION = 2 - USER_CRITERIA_ACROSS_ALL_SESSIONS = 3 - - -class UserExclusionDuration(proto.Enum): - r"""Enumerates options for how long an exclusion will last if a user - matches the ``userExclusionCriteria``. - """ - USER_EXCLUSION_DURATION_UNSPECIFIED = 0 - USER_EXCLUSION_TEMPORARY = 1 - USER_EXCLUSION_PERMANENT = 2 - - -class SessionCriteriaScoping(proto.Enum): - r"""Scoping specifies which events are considered when evaluating - if a session meets a criteria. - """ - SESSION_CRITERIA_SCOPING_UNSPECIFIED = 0 - SESSION_CRITERIA_WITHIN_SAME_EVENT = 1 - SESSION_CRITERIA_WITHIN_SAME_SESSION = 2 - - -class SessionExclusionDuration(proto.Enum): - r"""Enumerates options for how long an exclusion will last if a session - matches the ``sessionExclusionCriteria``. - """ - SESSION_EXCLUSION_DURATION_UNSPECIFIED = 0 - SESSION_EXCLUSION_TEMPORARY = 1 - SESSION_EXCLUSION_PERMANENT = 2 - - -class EventCriteriaScoping(proto.Enum): - r"""Scoping specifies which events are considered when evaluating - if an event meets a criteria. - """ - EVENT_CRITERIA_SCOPING_UNSPECIFIED = 0 - EVENT_CRITERIA_WITHIN_SAME_EVENT = 1 - - -class EventExclusionDuration(proto.Enum): - r"""Enumerates options for how long an exclusion will last if an event - matches the ``eventExclusionCriteria``. - """ - EVENT_EXCLUSION_DURATION_UNSPECIFIED = 0 - EVENT_EXCLUSION_PERMANENT = 1 - - -class MetricType(proto.Enum): - r"""A metric's value type.""" - METRIC_TYPE_UNSPECIFIED = 0 - TYPE_INTEGER = 1 - TYPE_FLOAT = 2 - TYPE_SECONDS = 4 - TYPE_MILLISECONDS = 5 - TYPE_MINUTES = 6 - TYPE_HOURS = 7 - TYPE_STANDARD = 8 - TYPE_CURRENCY = 9 - TYPE_FEET = 10 - TYPE_MILES = 11 - TYPE_METERS = 12 - TYPE_KILOMETERS = 13 - - -class DateRange(proto.Message): - r"""A contiguous set of days: startDate, startDate + 1, ..., - endDate. Requests are allowed up to 4 date ranges. - - Attributes: - start_date (str): - The inclusive start date for the query in the format - ``YYYY-MM-DD``. Cannot be after ``end_date``. The format - ``NdaysAgo``, ``yesterday``, or ``today`` is also accepted, - and in that case, the date is inferred based on the - property's reporting time zone. - end_date (str): - The inclusive end date for the query in the format - ``YYYY-MM-DD``. Cannot be before ``start_date``. The format - ``NdaysAgo``, ``yesterday``, or ``today`` is also accepted, - and in that case, the date is inferred based on the - property's reporting time zone. - name (str): - Assigns a name to this date range. The dimension - ``dateRange`` is valued to this name in a report response. - If set, cannot begin with ``date_range_`` or ``RESERVED_``. - If not set, date ranges are named by their zero based index - in the request: ``date_range_0``, ``date_range_1``, etc. - """ - - start_date: str = proto.Field( - proto.STRING, - number=1, - ) - end_date: str = proto.Field( - proto.STRING, - number=2, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - -class Dimension(proto.Message): - r"""Dimensions are attributes of your data. For example, the - dimension city indicates the city from which an event - originates. Dimension values in report responses are strings; - for example, the city could be "Paris" or "New York". - - Attributes: - name (str): - The name of the dimension. See the `API - Dimensions `__ - for the list of dimension names. - - If ``dimensionExpression`` is specified, ``name`` can be any - string that you would like within the allowed character set. - For example if a ``dimensionExpression`` concatenates - ``country`` and ``city``, you could call that dimension - ``countryAndCity``. Dimension names that you choose must - match the regular expression ``^[a-zA-Z0-9_]$``. - - Dimensions are referenced by ``name`` in - ``dimensionFilter``, ``orderBys``, ``dimensionExpression``, - and ``pivots``. - dimension_expression (google.analytics.data_v1alpha.types.DimensionExpression): - One dimension can be the result of an - expression of multiple dimensions. For example, - dimension "country, city": concatenate(country, - ", ", city). - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - dimension_expression: 'DimensionExpression' = proto.Field( - proto.MESSAGE, - number=2, - message='DimensionExpression', - ) - - -class DimensionExpression(proto.Message): - r"""Used to express a dimension which is the result of a formula of - multiple dimensions. Example usages: - - 1) lower_case(dimension) - 2) concatenate(dimension1, symbol, dimension2). - - 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: - lower_case (google.analytics.data_v1alpha.types.DimensionExpression.CaseExpression): - Used to convert a dimension value to lower - case. - - This field is a member of `oneof`_ ``one_expression``. - upper_case (google.analytics.data_v1alpha.types.DimensionExpression.CaseExpression): - Used to convert a dimension value to upper - case. - - This field is a member of `oneof`_ ``one_expression``. - concatenate (google.analytics.data_v1alpha.types.DimensionExpression.ConcatenateExpression): - Used to combine dimension values to a single - dimension. For example, dimension "country, - city": concatenate(country, ", ", city). - - This field is a member of `oneof`_ ``one_expression``. - """ - - class CaseExpression(proto.Message): - r"""Used to convert a dimension value to a single case. - - Attributes: - dimension_name (str): - Name of a dimension. The name must refer back - to a name in dimensions field of the request. - """ - - dimension_name: str = proto.Field( - proto.STRING, - number=1, - ) - - class ConcatenateExpression(proto.Message): - r"""Used to combine dimension values to a single dimension. - - Attributes: - dimension_names (MutableSequence[str]): - Names of dimensions. The names must refer - back to names in the dimensions field of the - request. - delimiter (str): - The delimiter placed between dimension names. - - Delimiters are often single characters such as "|" or "," - but can be longer strings. If a dimension value contains the - delimiter, both will be present in response with no - distinction. For example if dimension 1 value = "US,FR", - dimension 2 value = "JP", and delimiter = ",", then the - response will contain "US,FR,JP". - """ - - dimension_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - delimiter: str = proto.Field( - proto.STRING, - number=2, - ) - - lower_case: CaseExpression = proto.Field( - proto.MESSAGE, - number=4, - oneof='one_expression', - message=CaseExpression, - ) - upper_case: CaseExpression = proto.Field( - proto.MESSAGE, - number=5, - oneof='one_expression', - message=CaseExpression, - ) - concatenate: ConcatenateExpression = proto.Field( - proto.MESSAGE, - number=6, - oneof='one_expression', - message=ConcatenateExpression, - ) - - -class FilterExpression(proto.Message): - r"""To express dimension or metric filters. The fields in the - same FilterExpression 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.data_v1alpha.types.FilterExpressionList): - The FilterExpressions in and_group have an AND relationship. - - This field is a member of `oneof`_ ``expr``. - or_group (google.analytics.data_v1alpha.types.FilterExpressionList): - The FilterExpressions in or_group have an OR relationship. - - This field is a member of `oneof`_ ``expr``. - not_expression (google.analytics.data_v1alpha.types.FilterExpression): - The FilterExpression is NOT of not_expression. - - This field is a member of `oneof`_ ``expr``. - filter (google.analytics.data_v1alpha.types.Filter): - 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`_ ``expr``. - """ - - and_group: 'FilterExpressionList' = proto.Field( - proto.MESSAGE, - number=1, - oneof='expr', - message='FilterExpressionList', - ) - or_group: 'FilterExpressionList' = proto.Field( - proto.MESSAGE, - number=2, - oneof='expr', - message='FilterExpressionList', - ) - not_expression: 'FilterExpression' = proto.Field( - proto.MESSAGE, - number=3, - oneof='expr', - message='FilterExpression', - ) - filter: 'Filter' = proto.Field( - proto.MESSAGE, - number=4, - oneof='expr', - message='Filter', - ) - - -class FilterExpressionList(proto.Message): - r"""A list of filter expressions. - - Attributes: - expressions (MutableSequence[google.analytics.data_v1alpha.types.FilterExpression]): - A list of filter expressions. - """ - - expressions: MutableSequence['FilterExpression'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='FilterExpression', - ) - - -class Filter(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: - field_name (str): - The dimension name or metric name. Must be a - name defined in dimensions or metrics. - string_filter (google.analytics.data_v1alpha.types.StringFilter): - Strings related filter. - - This field is a member of `oneof`_ ``one_filter``. - in_list_filter (google.analytics.data_v1alpha.types.InListFilter): - A filter for in list values. - - This field is a member of `oneof`_ ``one_filter``. - numeric_filter (google.analytics.data_v1alpha.types.NumericFilter): - A filter for numeric or date values. - - This field is a member of `oneof`_ ``one_filter``. - between_filter (google.analytics.data_v1alpha.types.BetweenFilter): - A filter for between two values. - - This field is a member of `oneof`_ ``one_filter``. - """ - - field_name: str = proto.Field( - proto.STRING, - number=1, - ) - 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', - ) - - -class StringFilter(proto.Message): - r"""The filter for string - - Attributes: - match_type (google.analytics.data_v1alpha.types.StringFilter.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""" - 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 InListFilter(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 NumericFilter(proto.Message): - r"""Filters for numeric or date values. - - Attributes: - operation (google.analytics.data_v1alpha.types.NumericFilter.Operation): - The operation type for this filter. - value (google.analytics.data_v1alpha.types.NumericValue): - A numeric value or a date value. - """ - class Operation(proto.Enum): - r"""The operation applied to a numeric filter""" - 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 BetweenFilter(proto.Message): - r"""To express that the result needs to be between two numbers - (inclusive). - - Attributes: - from_value (google.analytics.data_v1alpha.types.NumericValue): - Begins with this number. - to_value (google.analytics.data_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 DimensionHeader(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: - name (str): - The dimension's name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class MetricHeader(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: - name (str): - The metric's name. - type_ (google.analytics.data_v1alpha.types.MetricType): - The metric's data type. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: 'MetricType' = proto.Field( - proto.ENUM, - number=2, - enum='MetricType', - ) - - -class Row(proto.Message): - r"""Report data for each row. For example if RunReportRequest contains: - - .. code:: none - - "dimensions": [ - { - "name": "eventName" - }, - { - "name": "countryId" - } - ], - "metrics": [ - { - "name": "eventCount" - } - ] - - One row with 'in_app_purchase' as the eventName, 'JP' as the - countryId, and 15 as the eventCount, would be: - - .. code:: none - - "dimensionValues": [ - { - "value": "in_app_purchase" - }, - { - "value": "JP" - } - ], - "metricValues": [ - { - "value": "15" - } - ] - - Attributes: - dimension_values (MutableSequence[google.analytics.data_v1alpha.types.DimensionValue]): - List of requested dimension values. In a PivotReport, - dimension_values are only listed for dimensions included in - a pivot. - metric_values (MutableSequence[google.analytics.data_v1alpha.types.MetricValue]): - List of requested visible metric values. - """ - - dimension_values: MutableSequence['DimensionValue'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='DimensionValue', - ) - metric_values: MutableSequence['MetricValue'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='MetricValue', - ) - - -class DimensionValue(proto.Message): - r"""The value of a dimension. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - value (str): - Value as a string if the dimension type is a - string. - - This field is a member of `oneof`_ ``one_value``. - """ - - value: str = proto.Field( - proto.STRING, - number=1, - oneof='one_value', - ) - - -class MetricValue(proto.Message): - r"""The value of a metric. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - value (str): - Measurement value. See MetricHeader for type. - - This field is a member of `oneof`_ ``one_value``. - """ - - value: str = proto.Field( - proto.STRING, - number=4, - oneof='one_value', - ) - - -class PropertyQuota(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.data_v1alpha.types.QuotaStatus): - Standard Analytics Properties can use up to - 25,000 tokens per day; Analytics 360 Properties - can use 250,000 tokens per day. Most requests - consume fewer than 10 tokens. - tokens_per_hour (google.analytics.data_v1alpha.types.QuotaStatus): - Standard Analytics Properties can use up to - 5,000 tokens per hour; Analytics 360 Properties - can use 50,000 tokens per hour. An API request - consumes a single number of tokens, and that - number is deducted from both the hourly and - daily quotas. - concurrent_requests (google.analytics.data_v1alpha.types.QuotaStatus): - Standard Analytics Properties can send up to - 10 concurrent requests; Analytics 360 Properties - can use up to 50 concurrent requests. - server_errors_per_project_per_hour (google.analytics.data_v1alpha.types.QuotaStatus): - Standard Analytics Properties and cloud - project pairs can have up to 10 server errors - per hour; Analytics 360 Properties and cloud - project pairs can have up to 50 server errors - per hour. - potentially_thresholded_requests_per_hour (google.analytics.data_v1alpha.types.QuotaStatus): - Analytics Properties can send up to 120 - requests with potentially thresholded dimensions - per hour. In a batch request, each report - request is individually counted for this quota - if the request contains potentially thresholded - dimensions. - """ - - tokens_per_day: 'QuotaStatus' = proto.Field( - proto.MESSAGE, - number=1, - message='QuotaStatus', - ) - tokens_per_hour: 'QuotaStatus' = proto.Field( - proto.MESSAGE, - number=2, - message='QuotaStatus', - ) - concurrent_requests: 'QuotaStatus' = proto.Field( - proto.MESSAGE, - number=3, - message='QuotaStatus', - ) - server_errors_per_project_per_hour: 'QuotaStatus' = proto.Field( - proto.MESSAGE, - number=4, - message='QuotaStatus', - ) - potentially_thresholded_requests_per_hour: 'QuotaStatus' = proto.Field( - proto.MESSAGE, - number=5, - message='QuotaStatus', - ) - - -class QuotaStatus(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, - ) - - -class FunnelBreakdown(proto.Message): - r"""Breakdowns add a dimension to the funnel table sub report - response. - - Attributes: - breakdown_dimension (google.analytics.data_v1alpha.types.Dimension): - The dimension column added to the funnel table sub report - response. The breakdown dimension breaks down each funnel - step. A valid ``breakdownDimension`` is required if - ``funnelBreakdown`` is specified. - limit (int): - The maximum number of distinct values of the breakdown - dimension to return in the response. A ``limit`` of ``5`` is - used if limit is not specified. Limit must exceed zero and - cannot exceed 15. - - This field is a member of `oneof`_ ``_limit``. - """ - - breakdown_dimension: 'Dimension' = proto.Field( - proto.MESSAGE, - number=1, - message='Dimension', - ) - limit: int = proto.Field( - proto.INT64, - number=2, - optional=True, - ) - - -class FunnelNextAction(proto.Message): - r"""Next actions state the value for a dimension after the user has - achieved a step but before the same user has achieved the next step. - For example if the ``nextActionDimension`` is ``eventName``, then - ``nextActionDimension`` in the ``i``\ th funnel step row will return - first event after the event that qualified the user into the - ``i``\ th funnel step but before the user achieved the ``i+1``\ th - funnel step. - - Attributes: - next_action_dimension (google.analytics.data_v1alpha.types.Dimension): - The dimension column added to the funnel visualization sub - report response. The next action dimension returns the next - dimension value of this dimension after the user has - attained the ``i``\ th funnel step. - - ``nextActionDimension`` currently only supports - ``eventName`` and most Page / Screen dimensions like - ``pageTitle`` and ``pagePath``. ``nextActionDimension`` - cannot be a dimension expression. - limit (int): - The maximum number of distinct values of the breakdown - dimension to return in the response. A ``limit`` of ``5`` is - used if limit is not specified. Limit must exceed zero and - cannot exceed 5. - - This field is a member of `oneof`_ ``_limit``. - """ - - next_action_dimension: 'Dimension' = proto.Field( - proto.MESSAGE, - number=1, - message='Dimension', - ) - limit: int = proto.Field( - proto.INT64, - number=2, - optional=True, - ) - - -class Funnel(proto.Message): - r"""Configures the funnel in a funnel report request. A funnel - reports on users as they pass through a sequence of steps. - Funnel exploration lets you visualize the steps your users take - to complete a task and quickly see how well they are succeeding - or failing at each step. For example, how do prospects become - shoppers and then become buyers? How do one time buyers become - repeat buyers? With this information, you can improve - inefficient or abandoned customer journeys. - - Attributes: - is_open_funnel (bool): - In an open funnel, users can enter the funnel - in any step, and in a closed funnel, users must - enter the funnel in the first step. Optional. If - unspecified, a closed funnel is used. - steps (MutableSequence[google.analytics.data_v1alpha.types.FunnelStep]): - The sequential steps of this funnel. - """ - - is_open_funnel: bool = proto.Field( - proto.BOOL, - number=1, - ) - steps: MutableSequence['FunnelStep'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='FunnelStep', - ) - - -class FunnelStep(proto.Message): - r"""Steps define the user journey you want to measure. Steps - contain one or more conditions that your users must meet to be - included in that step of the funnel journey. - - Attributes: - name (str): - The distinctive name for this step. If unspecified, steps - will be named by a 1 based indexed name (i.e. "0. ", "1. ", - etc.). This name defines string value returned by the - ``funnelStepName`` dimension. For example, specifying - ``name = Purchase`` in the request's third funnel step will - produce ``3. Purchase`` in the funnel report response. - is_directly_followed_by (bool): - If true, this step must directly follow the previous step. - If false, there can be events between the previous step and - this step. If unspecified, ``isDirectlyFollowedBy`` is - treated as false. - within_duration_from_prior_step (google.protobuf.duration_pb2.Duration): - If specified, this step must complete within this duration - of the completion of the prior step. - ``withinDurationFromPriorStep`` is inclusive of the endpoint - at the microsecond granularity. For example a duration of 5 - seconds can be completed at 4.9 or 5.0 seconds, but not 5 - seconds and 1 microsecond. - - ``withinDurationFromPriorStep`` is optional, and if - unspecified, steps may be separated by any time duration. - - This field is a member of `oneof`_ ``_within_duration_from_prior_step``. - filter_expression (google.analytics.data_v1alpha.types.FunnelFilterExpression): - The condition that your users must meet to be - included in this step of the funnel journey. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - is_directly_followed_by: bool = proto.Field( - proto.BOOL, - number=2, - ) - within_duration_from_prior_step: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - optional=True, - message=duration_pb2.Duration, - ) - filter_expression: 'FunnelFilterExpression' = proto.Field( - proto.MESSAGE, - number=4, - message='FunnelFilterExpression', - ) - - -class FunnelSubReport(proto.Message): - r"""Funnel sub reports contain the dimension and metric data - values. For example, 12 users reached the second step of the - funnel. - - Attributes: - dimension_headers (MutableSequence[google.analytics.data_v1alpha.types.DimensionHeader]): - Describes dimension columns. Funnel reports - always include the funnel step dimension in sub - report responses. Additional dimensions like - breakdowns, dates, and next actions may be - present in the response if requested. - metric_headers (MutableSequence[google.analytics.data_v1alpha.types.MetricHeader]): - Describes metric columns. Funnel reports - always include active users in sub report - responses. The funnel table includes additional - metrics like completion rate, abandonments, and - abandonments rate. - rows (MutableSequence[google.analytics.data_v1alpha.types.Row]): - Rows of dimension value combinations and - metric values in the report. - metadata (google.analytics.data_v1alpha.types.FunnelResponseMetadata): - Metadata for the funnel report. - """ - - dimension_headers: MutableSequence['DimensionHeader'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='DimensionHeader', - ) - metric_headers: MutableSequence['MetricHeader'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='MetricHeader', - ) - rows: MutableSequence['Row'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Row', - ) - metadata: 'FunnelResponseMetadata' = proto.Field( - proto.MESSAGE, - number=4, - message='FunnelResponseMetadata', - ) - - -class UserSegment(proto.Message): - r"""User segments are subsets of users who engaged with your site - or app. For example, users who have previously purchased; users - who added items to their shopping carts, but didn’t complete a - purchase. - - Attributes: - user_inclusion_criteria (google.analytics.data_v1alpha.types.UserSegmentCriteria): - Defines which users are included in this - segment. Optional. - exclusion (google.analytics.data_v1alpha.types.UserSegmentExclusion): - Defines which users are excluded in this - segment. Optional. - """ - - user_inclusion_criteria: 'UserSegmentCriteria' = proto.Field( - proto.MESSAGE, - number=1, - message='UserSegmentCriteria', - ) - exclusion: 'UserSegmentExclusion' = proto.Field( - proto.MESSAGE, - number=2, - message='UserSegmentExclusion', - ) - - -class UserSegmentCriteria(proto.Message): - r"""A user matches a criteria if the user's events meet the - conditions in the criteria. - - Attributes: - and_condition_groups (MutableSequence[google.analytics.data_v1alpha.types.UserSegmentConditionGroup]): - A user matches this criteria if the user matches each of - these ``andConditionGroups`` and each of the - ``andSequenceGroups``. ``andConditionGroups`` may be empty - if ``andSequenceGroups`` are specified. - and_sequence_groups (MutableSequence[google.analytics.data_v1alpha.types.UserSegmentSequenceGroup]): - A user matches this criteria if the user matches each of - these ``andSequenceGroups`` and each of the - ``andConditionGroups``. ``andSequenceGroups`` may be empty - if ``andConditionGroups`` are specified. - """ - - and_condition_groups: MutableSequence['UserSegmentConditionGroup'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='UserSegmentConditionGroup', - ) - and_sequence_groups: MutableSequence['UserSegmentSequenceGroup'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='UserSegmentSequenceGroup', - ) - - -class UserSegmentConditionGroup(proto.Message): - r"""Conditions tell Analytics what data to include in or exclude - from the segment. - - Attributes: - condition_scoping (google.analytics.data_v1alpha.types.UserCriteriaScoping): - Data is included or excluded from the segment based on if it - matches the condition group. This scoping defines how many - events the ``segmentFilterExpression`` is evaluated on - before the condition group is determined to be matched or - not. For example if - ``conditionScoping = USER_CRITERIA_WITHIN_SAME_SESSION``, - the expression is evaluated on all events in a session, and - then, the condition group is determined to be matched or not - for this user. For example if - ``conditionScoping = USER_CRITERIA_WITHIN_SAME_EVENT``, the - expression is evaluated on a single event, and then, the - condition group is determined to be matched or not for this - user. - - Optional. If unspecified, - ``conditionScoping = ACROSS_ALL_SESSIONS`` is used. - segment_filter_expression (google.analytics.data_v1alpha.types.SegmentFilterExpression): - Data is included or excluded from the segment - based on if it matches this expression. - Expressions express criteria on dimension, - metrics, and/or parameters. - """ - - condition_scoping: 'UserCriteriaScoping' = proto.Field( - proto.ENUM, - number=1, - enum='UserCriteriaScoping', - ) - segment_filter_expression: 'SegmentFilterExpression' = proto.Field( - proto.MESSAGE, - number=2, - message='SegmentFilterExpression', - ) - - -class UserSegmentSequenceGroup(proto.Message): - r"""Define conditions that must occur in a specific order for the - user to be a member of the segment. - - Attributes: - sequence_scoping (google.analytics.data_v1alpha.types.UserCriteriaScoping): - All sequence steps must be satisfied in the scoping for the - user to match the sequence. For example if - ``sequenceScoping = USER_CRITERIA_WITHIN_SAME_SESSION``, all - sequence steps must complete within one session for the user - to match the sequence. - ``sequenceScoping = USER_CRITERIA_WITHIN_SAME_EVENT`` is not - supported. - - Optional. If unspecified, - ``conditionScoping = ACROSS_ALL_SESSIONS`` is used. - sequence_maximum_duration (google.protobuf.duration_pb2.Duration): - Defines the time period in which the whole sequence must - occur; for example, 30 Minutes. ``sequenceMaximumDuration`` - is inclusive of the endpoint at the microsecond granularity. - For example a sequence with a maximum duration of 5 seconds - can be completed at 4.9 or 5.0 seconds, but not 5 seconds - and 1 microsecond. - - ``sequenceMaximumDuration`` is optional, and if unspecified, - sequences can be completed in any time duration. - user_sequence_steps (MutableSequence[google.analytics.data_v1alpha.types.UserSequenceStep]): - An ordered sequence of condition steps. A user's events must - complete each step in order for the user to match the - ``UserSegmentSequenceGroup``. - """ - - sequence_scoping: 'UserCriteriaScoping' = proto.Field( - proto.ENUM, - number=1, - enum='UserCriteriaScoping', - ) - sequence_maximum_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - user_sequence_steps: MutableSequence['UserSequenceStep'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='UserSequenceStep', - ) - - -class UserSequenceStep(proto.Message): - r"""A condition that must occur in the specified step order for - this user to match the sequence. - - Attributes: - is_directly_followed_by (bool): - If true, the event satisfying this step must be the very - next event after the event satifying the last step. If - false, this step indirectly follows the prior step; for - example, there may be events between the prior step and this - step. ``isDirectlyFollowedBy`` must be false for the first - step. - step_scoping (google.analytics.data_v1alpha.types.UserCriteriaScoping): - This sequence step must be satisfied in the scoping for the - user to match the sequence. For example if - ``sequenceScoping = WITHIN_SAME_SESSION``, this sequence - steps must complete within one session for the user to match - the sequence. ``stepScoping = ACROSS_ALL_SESSIONS`` is only - allowed if the ``sequenceScoping = ACROSS_ALL_SESSIONS``. - - Optional. If unspecified, ``stepScoping`` uses the same - ``UserCriteriaScoping`` as the ``sequenceScoping``. - segment_filter_expression (google.analytics.data_v1alpha.types.SegmentFilterExpression): - A user matches this sequence step if their - events match this expression. Expressions - express criteria on dimension, metrics, and/or - parameters. - """ - - is_directly_followed_by: bool = proto.Field( - proto.BOOL, - number=1, - ) - step_scoping: 'UserCriteriaScoping' = proto.Field( - proto.ENUM, - number=2, - enum='UserCriteriaScoping', - ) - segment_filter_expression: 'SegmentFilterExpression' = proto.Field( - proto.MESSAGE, - number=3, - message='SegmentFilterExpression', - ) - - -class UserSegmentExclusion(proto.Message): - r"""Specifies which users are excluded in this segment. - - Attributes: - user_exclusion_duration (google.analytics.data_v1alpha.types.UserExclusionDuration): - Specifies how long an exclusion will last if a user matches - the ``userExclusionCriteria``. - - Optional. If unspecified, ``userExclusionDuration`` of - ``USER_EXCLUSION_TEMPORARY`` is used. - user_exclusion_criteria (google.analytics.data_v1alpha.types.UserSegmentCriteria): - If a user meets this condition, the user is excluded from - membership in the segment for the ``userExclusionDuration``. - """ - - user_exclusion_duration: 'UserExclusionDuration' = proto.Field( - proto.ENUM, - number=1, - enum='UserExclusionDuration', - ) - user_exclusion_criteria: 'UserSegmentCriteria' = proto.Field( - proto.MESSAGE, - number=2, - message='UserSegmentCriteria', - ) - - -class SessionSegment(proto.Message): - r"""Session segments are subsets of the sessions that occurred on - your site or app: for example, all the sessions that originated - from a particular advertising campaign. - - Attributes: - session_inclusion_criteria (google.analytics.data_v1alpha.types.SessionSegmentCriteria): - Defines which sessions are included in this - segment. Optional. - exclusion (google.analytics.data_v1alpha.types.SessionSegmentExclusion): - Defines which sessions are excluded in this - segment. Optional. - """ - - session_inclusion_criteria: 'SessionSegmentCriteria' = proto.Field( - proto.MESSAGE, - number=1, - message='SessionSegmentCriteria', - ) - exclusion: 'SessionSegmentExclusion' = proto.Field( - proto.MESSAGE, - number=2, - message='SessionSegmentExclusion', - ) - - -class SessionSegmentCriteria(proto.Message): - r"""A session matches a criteria if the session's events meet the - conditions in the criteria. - - Attributes: - and_condition_groups (MutableSequence[google.analytics.data_v1alpha.types.SessionSegmentConditionGroup]): - A session matches this criteria if the session matches each - of these ``andConditionGroups``. - """ - - and_condition_groups: MutableSequence['SessionSegmentConditionGroup'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SessionSegmentConditionGroup', - ) - - -class SessionSegmentConditionGroup(proto.Message): - r"""Conditions tell Analytics what data to include in or exclude - from the segment. - - Attributes: - condition_scoping (google.analytics.data_v1alpha.types.SessionCriteriaScoping): - Data is included or excluded from the segment based on if it - matches the condition group. This scoping defines how many - events the ``segmentFilterExpression`` is evaluated on - before the condition group is determined to be matched or - not. For example if - ``conditionScoping = SESSION_CRITERIA_WITHIN_SAME_SESSION``, - the expression is evaluated on all events in a session, and - then, the condition group is determined to be matched or not - for this session. For example if - ``conditionScoping = SESSION_CRITERIA_WITHIN_SAME_EVENT``, - the expression is evaluated on a single event, and then, the - condition group is determined to be matched or not for this - session. - - Optional. If unspecified, a ``conditionScoping`` of - ``WITHIN_SAME_SESSION`` is used. - segment_filter_expression (google.analytics.data_v1alpha.types.SegmentFilterExpression): - Data is included or excluded from the segment - based on if it matches this expression. - Expressions express criteria on dimension, - metrics, and/or parameters. - """ - - condition_scoping: 'SessionCriteriaScoping' = proto.Field( - proto.ENUM, - number=1, - enum='SessionCriteriaScoping', - ) - segment_filter_expression: 'SegmentFilterExpression' = proto.Field( - proto.MESSAGE, - number=2, - message='SegmentFilterExpression', - ) - - -class SessionSegmentExclusion(proto.Message): - r"""Specifies which sessions are excluded in this segment. - - Attributes: - session_exclusion_duration (google.analytics.data_v1alpha.types.SessionExclusionDuration): - Specifies how long an exclusion will last if a session - matches the ``sessionExclusionCriteria``. - - Optional. If unspecified, a ``sessionExclusionDuration`` of - ``SESSION_EXCLUSION_TEMPORARY`` is used. - session_exclusion_criteria (google.analytics.data_v1alpha.types.SessionSegmentCriteria): - If a session meets this condition, the session is excluded - from membership in the segment for the - ``sessionExclusionDuration``. - """ - - session_exclusion_duration: 'SessionExclusionDuration' = proto.Field( - proto.ENUM, - number=1, - enum='SessionExclusionDuration', - ) - session_exclusion_criteria: 'SessionSegmentCriteria' = proto.Field( - proto.MESSAGE, - number=2, - message='SessionSegmentCriteria', - ) - - -class EventSegment(proto.Message): - r"""Event segments are subsets of events that were triggered on your - site or app. for example, all purchase events made in a particular - location; app_exception events that occurred on a specific operating - system. - - Attributes: - event_inclusion_criteria (google.analytics.data_v1alpha.types.EventSegmentCriteria): - Defines which events are included in this - segment. Optional. - exclusion (google.analytics.data_v1alpha.types.EventSegmentExclusion): - Defines which events are excluded in this - segment. Optional. - """ - - event_inclusion_criteria: 'EventSegmentCriteria' = proto.Field( - proto.MESSAGE, - number=1, - message='EventSegmentCriteria', - ) - exclusion: 'EventSegmentExclusion' = proto.Field( - proto.MESSAGE, - number=2, - message='EventSegmentExclusion', - ) - - -class EventSegmentCriteria(proto.Message): - r"""An event matches a criteria if the event meet the conditions - in the criteria. - - Attributes: - and_condition_groups (MutableSequence[google.analytics.data_v1alpha.types.EventSegmentConditionGroup]): - An event matches this criteria if the event matches each of - these ``andConditionGroups``. - """ - - and_condition_groups: MutableSequence['EventSegmentConditionGroup'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='EventSegmentConditionGroup', - ) - - -class EventSegmentConditionGroup(proto.Message): - r"""Conditions tell Analytics what data to include in or exclude - from the segment. - - Attributes: - condition_scoping (google.analytics.data_v1alpha.types.EventCriteriaScoping): - ``conditionScoping`` should always be - ``EVENT_CRITERIA_WITHIN_SAME_EVENT``. - - Optional. If unspecified, a ``conditionScoping`` of - ``EVENT_CRITERIA_WITHIN_SAME_EVENT`` is used. - segment_filter_expression (google.analytics.data_v1alpha.types.SegmentFilterExpression): - Data is included or excluded from the segment - based on if it matches this expression. - Expressions express criteria on dimension, - metrics, and/or parameters. - """ - - condition_scoping: 'EventCriteriaScoping' = proto.Field( - proto.ENUM, - number=1, - enum='EventCriteriaScoping', - ) - segment_filter_expression: 'SegmentFilterExpression' = proto.Field( - proto.MESSAGE, - number=2, - message='SegmentFilterExpression', - ) - - -class EventSegmentExclusion(proto.Message): - r"""Specifies which events are excluded in this segment. - - Attributes: - event_exclusion_duration (google.analytics.data_v1alpha.types.EventExclusionDuration): - ``eventExclusionDuration`` should always be - ``PERMANENTLY_EXCLUDE``. - - Optional. If unspecified, an ``eventExclusionDuration`` of - ``EVENT_EXCLUSION_PERMANENT`` is used. - event_exclusion_criteria (google.analytics.data_v1alpha.types.EventSegmentCriteria): - If an event meets this condition, the event is excluded from - membership in the segment for the - ``eventExclusionDuration``. - """ - - event_exclusion_duration: 'EventExclusionDuration' = proto.Field( - proto.ENUM, - number=1, - enum='EventExclusionDuration', - ) - event_exclusion_criteria: 'EventSegmentCriteria' = proto.Field( - proto.MESSAGE, - number=2, - message='EventSegmentCriteria', - ) - - -class Segment(proto.Message): - r"""A segment is a subset of your Analytics data. For example, of your - entire set of users, one segment might be users from a particular - country or city. Another segment might be users who purchase a - particular line of products or who visit a specific part of your - site or trigger certain events in your app. - - To learn more, see `GA4 Segment - Builder `__. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - The name for this segment. If unspecified, segments are - named "Segment". This name defines string value returned by - the ``segment`` dimension. The ``segment`` dimension - prefixes segment names by the 1-based index number of the - segment in the request (i.e. "1. Segment", "2. Segment", - etc.). - user_segment (google.analytics.data_v1alpha.types.UserSegment): - User segments are subsets of users who - engaged with your site or app. - - This field is a member of `oneof`_ ``one_segment_scope``. - session_segment (google.analytics.data_v1alpha.types.SessionSegment): - Session segments are subsets of the sessions - that occurred on your site or app. - - This field is a member of `oneof`_ ``one_segment_scope``. - event_segment (google.analytics.data_v1alpha.types.EventSegment): - Event segments are subsets of events that - were triggered on your site or app. - - This field is a member of `oneof`_ ``one_segment_scope``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - user_segment: 'UserSegment' = proto.Field( - proto.MESSAGE, - number=2, - oneof='one_segment_scope', - message='UserSegment', - ) - session_segment: 'SessionSegment' = proto.Field( - proto.MESSAGE, - number=3, - oneof='one_segment_scope', - message='SessionSegment', - ) - event_segment: 'EventSegment' = proto.Field( - proto.MESSAGE, - number=4, - oneof='one_segment_scope', - message='EventSegment', - ) - - -class SegmentFilterExpression(proto.Message): - r"""Expresses combinations of segment 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.data_v1alpha.types.SegmentFilterExpressionList): - The SegmentFilterExpression in ``andGroup`` have an AND - relationship. - - This field is a member of `oneof`_ ``expr``. - or_group (google.analytics.data_v1alpha.types.SegmentFilterExpressionList): - The SegmentFilterExpression in ``orGroup`` have an OR - relationship. - - This field is a member of `oneof`_ ``expr``. - not_expression (google.analytics.data_v1alpha.types.SegmentFilterExpression): - The SegmentFilterExpression is NOT of ``notExpression``. - - This field is a member of `oneof`_ ``expr``. - segment_filter (google.analytics.data_v1alpha.types.SegmentFilter): - A primitive segment filter. - - This field is a member of `oneof`_ ``expr``. - segment_event_filter (google.analytics.data_v1alpha.types.SegmentEventFilter): - Creates a filter that matches events of a - single event name. If a parameter filter - expression is specified, only the subset of - events that match both the single event name and - the parameter filter expressions match this - event filter. - - This field is a member of `oneof`_ ``expr``. - """ - - and_group: 'SegmentFilterExpressionList' = proto.Field( - proto.MESSAGE, - number=1, - oneof='expr', - message='SegmentFilterExpressionList', - ) - or_group: 'SegmentFilterExpressionList' = proto.Field( - proto.MESSAGE, - number=2, - oneof='expr', - message='SegmentFilterExpressionList', - ) - not_expression: 'SegmentFilterExpression' = proto.Field( - proto.MESSAGE, - number=3, - oneof='expr', - message='SegmentFilterExpression', - ) - segment_filter: 'SegmentFilter' = proto.Field( - proto.MESSAGE, - number=4, - oneof='expr', - message='SegmentFilter', - ) - segment_event_filter: 'SegmentEventFilter' = proto.Field( - proto.MESSAGE, - number=5, - oneof='expr', - message='SegmentEventFilter', - ) - - -class SegmentFilterExpressionList(proto.Message): - r"""A list of segment filter expressions. - - Attributes: - expressions (MutableSequence[google.analytics.data_v1alpha.types.SegmentFilterExpression]): - The list of segment filter expressions - """ - - expressions: MutableSequence['SegmentFilterExpression'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SegmentFilterExpression', - ) - - -class SegmentFilter(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: - field_name (str): - The dimension name or metric name. - string_filter (google.analytics.data_v1alpha.types.StringFilter): - Strings related filter. - - This field is a member of `oneof`_ ``one_filter``. - in_list_filter (google.analytics.data_v1alpha.types.InListFilter): - A filter for in list values. - - This field is a member of `oneof`_ ``one_filter``. - numeric_filter (google.analytics.data_v1alpha.types.NumericFilter): - A filter for numeric or date values. - - This field is a member of `oneof`_ ``one_filter``. - between_filter (google.analytics.data_v1alpha.types.BetweenFilter): - A filter for between two values. - - This field is a member of `oneof`_ ``one_filter``. - filter_scoping (google.analytics.data_v1alpha.types.SegmentFilterScoping): - Specifies the scope for the filter. - """ - - field_name: str = proto.Field( - proto.STRING, - number=1, - ) - string_filter: 'StringFilter' = proto.Field( - proto.MESSAGE, - number=4, - oneof='one_filter', - message='StringFilter', - ) - in_list_filter: 'InListFilter' = proto.Field( - proto.MESSAGE, - number=5, - oneof='one_filter', - message='InListFilter', - ) - numeric_filter: 'NumericFilter' = proto.Field( - proto.MESSAGE, - number=6, - oneof='one_filter', - message='NumericFilter', - ) - between_filter: 'BetweenFilter' = proto.Field( - proto.MESSAGE, - number=7, - oneof='one_filter', - message='BetweenFilter', - ) - filter_scoping: 'SegmentFilterScoping' = proto.Field( - proto.MESSAGE, - number=8, - message='SegmentFilterScoping', - ) - - -class SegmentFilterScoping(proto.Message): - r"""Scopings specify how the dimensions & metrics of multiple - events should be considered when evaluating a segment filter. - - Attributes: - at_any_point_in_time (bool): - If ``atAnyPointInTime`` is true, this filter evaluates to - true for all events if it evaluates to true for any event in - the date range of the request. - - This ``atAnyPointInTime`` parameter does not extend the date - range of events in the report. If ``atAnyPointInTime`` is - true, only events within the report's date range are - considered when evaluating this filter. - - This ``atAnyPointInTime`` is only able to be specified if - the criteria scoping is ``ACROSS_ALL_SESSIONS`` and is not - able to be specified in sequences. - - If the criteria scoping is ``ACROSS_ALL_SESSIONS``, - ``atAnyPointInTime`` = false is used if unspecified. - - This field is a member of `oneof`_ ``_at_any_point_in_time``. - """ - - at_any_point_in_time: bool = proto.Field( - proto.BOOL, - number=1, - optional=True, - ) - - -class SegmentEventFilter(proto.Message): - r"""Creates a filter that matches events of a single event name. - If a parameter filter expression 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): - This filter matches events of this single - event name. Event name is required. - - This field is a member of `oneof`_ ``_event_name``. - segment_parameter_filter_expression (google.analytics.data_v1alpha.types.SegmentParameterFilterExpression): - If specified, this filter matches events that - match both the single event name and the - parameter filter expressions. - Inside the parameter filter expression, only - parameter filters are available. - - This field is a member of `oneof`_ ``_segment_parameter_filter_expression``. - """ - - event_name: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - segment_parameter_filter_expression: 'SegmentParameterFilterExpression' = proto.Field( - proto.MESSAGE, - number=2, - optional=True, - message='SegmentParameterFilterExpression', - ) - - -class SegmentParameterFilterExpression(proto.Message): - r"""Expresses combinations of segment filter on parameters. - - 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.data_v1alpha.types.SegmentParameterFilterExpressionList): - The SegmentParameterFilterExpression in ``andGroup`` have an - AND relationship. - - This field is a member of `oneof`_ ``expr``. - or_group (google.analytics.data_v1alpha.types.SegmentParameterFilterExpressionList): - The SegmentParameterFilterExpression in ``orGroup`` have an - OR relationship. - - This field is a member of `oneof`_ ``expr``. - not_expression (google.analytics.data_v1alpha.types.SegmentParameterFilterExpression): - The SegmentParameterFilterExpression is NOT of - ``notExpression``. - - This field is a member of `oneof`_ ``expr``. - segment_parameter_filter (google.analytics.data_v1alpha.types.SegmentParameterFilter): - A primitive segment parameter filter. - - This field is a member of `oneof`_ ``expr``. - """ - - and_group: 'SegmentParameterFilterExpressionList' = proto.Field( - proto.MESSAGE, - number=1, - oneof='expr', - message='SegmentParameterFilterExpressionList', - ) - or_group: 'SegmentParameterFilterExpressionList' = proto.Field( - proto.MESSAGE, - number=2, - oneof='expr', - message='SegmentParameterFilterExpressionList', - ) - not_expression: 'SegmentParameterFilterExpression' = proto.Field( - proto.MESSAGE, - number=3, - oneof='expr', - message='SegmentParameterFilterExpression', - ) - segment_parameter_filter: 'SegmentParameterFilter' = proto.Field( - proto.MESSAGE, - number=4, - oneof='expr', - message='SegmentParameterFilter', - ) - - -class SegmentParameterFilterExpressionList(proto.Message): - r"""A list of segment parameter filter expressions. - - Attributes: - expressions (MutableSequence[google.analytics.data_v1alpha.types.SegmentParameterFilterExpression]): - The list of segment parameter filter - expressions. - """ - - expressions: MutableSequence['SegmentParameterFilterExpression'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SegmentParameterFilterExpression', - ) - - -class SegmentParameterFilter(proto.Message): - r"""An expression to filter parameter values in a segment. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - event_parameter_name (str): - This filter will be evaluated on the specified event - parameter. Event parameters are logged as parameters of the - event. Event parameters include fields like - "firebase_screen" & "currency". - - Event parameters can only be used in segments & funnels and - can only be used in a descendent filter from an EventFilter. - In a descendent filter from an EventFilter either event or - item parameters should be used. - - This field is a member of `oneof`_ ``one_parameter``. - item_parameter_name (str): - This filter will be evaluated on the specified item - parameter. Item parameters are logged as parameters in the - item array. Item parameters include fields like "item_name" - & "item_category". - - Item parameters can only be used in segments & funnels and - can only be used in a descendent filter from an EventFilter. - In a descendent filter from an EventFilter either event or - item parameters should be used. - - Item parameters are only available in ecommerce events. To - learn more about ecommerce events, see the [Measure - ecommerce] - (https://developers.google.com/analytics/devguides/collection/ga4/ecommerce) - guide. - - This field is a member of `oneof`_ ``one_parameter``. - string_filter (google.analytics.data_v1alpha.types.StringFilter): - Strings related filter. - - This field is a member of `oneof`_ ``one_filter``. - in_list_filter (google.analytics.data_v1alpha.types.InListFilter): - A filter for in list values. - - This field is a member of `oneof`_ ``one_filter``. - numeric_filter (google.analytics.data_v1alpha.types.NumericFilter): - A filter for numeric or date values. - - This field is a member of `oneof`_ ``one_filter``. - between_filter (google.analytics.data_v1alpha.types.BetweenFilter): - A filter for between two values. - - This field is a member of `oneof`_ ``one_filter``. - filter_scoping (google.analytics.data_v1alpha.types.SegmentParameterFilterScoping): - Specifies the scope for the filter. - """ - - event_parameter_name: str = proto.Field( - proto.STRING, - number=1, - oneof='one_parameter', - ) - item_parameter_name: str = proto.Field( - proto.STRING, - number=2, - oneof='one_parameter', - ) - string_filter: 'StringFilter' = proto.Field( - proto.MESSAGE, - number=4, - oneof='one_filter', - message='StringFilter', - ) - in_list_filter: 'InListFilter' = proto.Field( - proto.MESSAGE, - number=5, - oneof='one_filter', - message='InListFilter', - ) - numeric_filter: 'NumericFilter' = proto.Field( - proto.MESSAGE, - number=6, - oneof='one_filter', - message='NumericFilter', - ) - between_filter: 'BetweenFilter' = proto.Field( - proto.MESSAGE, - number=7, - oneof='one_filter', - message='BetweenFilter', - ) - filter_scoping: 'SegmentParameterFilterScoping' = proto.Field( - proto.MESSAGE, - number=8, - message='SegmentParameterFilterScoping', - ) - - -class SegmentParameterFilterScoping(proto.Message): - r"""Scopings specify how multiple events should be considered - when evaluating a segment parameter filter. - - Attributes: - in_any_n_day_period (int): - Accumulates the parameter over the specified period of days - before applying the filter. Only supported if criteria - scoping is ``ACROSS_ALL_SESSIONS`` or - ``WITHIN_SAME_SESSION``. Only supported if the parameter is - ``event_count``. - - For example if ``inAnyNDayPeriod`` is 3, the event_name is - "purchase", the event parameter is "event_count", and the - Filter's criteria is greater than 5, this filter will - accumulate the event count of purchase events over every 3 - consecutive day period in the report's date range; a user - will pass this Filter's criteria to be included in this - segment if their count of purchase events exceeds 5 in any 3 - consecutive day period. For example, the periods 2021-11-01 - to 2021-11-03, 2021-11-02 to 2021-11-04, 2021-11-03 to - 2021-11-05, and etc. will be considered. - - The date range is not extended for the purpose of having a - full N day window near the start of the date range. For - example if a report is for 2021-11-01 to 2021-11-10 and - ``inAnyNDayPeriod`` = 3, the first two day period will be - effectively shortened because no event data outside the - report's date range will be read. For example, the first - four periods will effectively be: 2021-11-01 to 2021-11-01, - 2021-11-01 to 2021-11-02, 2021-11-01 to 2021-11-03, and - 2021-11-02 to 2021-11-04. - - ``inAnyNDayPeriod`` is optional. If not specified, the - ``segmentParameterFilter`` is applied to each event - individually. - - This field is a member of `oneof`_ ``_in_any_n_day_period``. - """ - - in_any_n_day_period: int = proto.Field( - proto.INT64, - number=1, - optional=True, - ) - - -class FunnelFilterExpression(proto.Message): - r"""Expresses combinations of funnel 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.data_v1alpha.types.FunnelFilterExpressionList): - The FunnelFilterExpression in ``andGroup`` have an AND - relationship. - - This field is a member of `oneof`_ ``expr``. - or_group (google.analytics.data_v1alpha.types.FunnelFilterExpressionList): - The FunnelFilterExpression in ``orGroup`` have an OR - relationship. - - This field is a member of `oneof`_ ``expr``. - not_expression (google.analytics.data_v1alpha.types.FunnelFilterExpression): - The FunnelFilterExpression is NOT of ``notExpression``. - - This field is a member of `oneof`_ ``expr``. - funnel_field_filter (google.analytics.data_v1alpha.types.FunnelFieldFilter): - A funnel filter for a dimension or metric. - - This field is a member of `oneof`_ ``expr``. - funnel_event_filter (google.analytics.data_v1alpha.types.FunnelEventFilter): - Creates a filter that matches events of a - single event name. If a parameter filter - expression is specified, only the subset of - events that match both the single event name and - the parameter filter expressions match this - event filter. - - This field is a member of `oneof`_ ``expr``. - """ - - and_group: 'FunnelFilterExpressionList' = proto.Field( - proto.MESSAGE, - number=1, - oneof='expr', - message='FunnelFilterExpressionList', - ) - or_group: 'FunnelFilterExpressionList' = proto.Field( - proto.MESSAGE, - number=2, - oneof='expr', - message='FunnelFilterExpressionList', - ) - not_expression: 'FunnelFilterExpression' = proto.Field( - proto.MESSAGE, - number=3, - oneof='expr', - message='FunnelFilterExpression', - ) - funnel_field_filter: 'FunnelFieldFilter' = proto.Field( - proto.MESSAGE, - number=4, - oneof='expr', - message='FunnelFieldFilter', - ) - funnel_event_filter: 'FunnelEventFilter' = proto.Field( - proto.MESSAGE, - number=5, - oneof='expr', - message='FunnelEventFilter', - ) - - -class FunnelFilterExpressionList(proto.Message): - r"""A list of funnel filter expressions. - - Attributes: - expressions (MutableSequence[google.analytics.data_v1alpha.types.FunnelFilterExpression]): - The list of funnel filter expressions. - """ - - expressions: MutableSequence['FunnelFilterExpression'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='FunnelFilterExpression', - ) - - -class FunnelFieldFilter(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: - field_name (str): - The dimension name or metric name. - string_filter (google.analytics.data_v1alpha.types.StringFilter): - Strings related filter. - - This field is a member of `oneof`_ ``one_filter``. - in_list_filter (google.analytics.data_v1alpha.types.InListFilter): - A filter for in list values. - - This field is a member of `oneof`_ ``one_filter``. - numeric_filter (google.analytics.data_v1alpha.types.NumericFilter): - A filter for numeric or date values. - - This field is a member of `oneof`_ ``one_filter``. - between_filter (google.analytics.data_v1alpha.types.BetweenFilter): - A filter for between two values. - - This field is a member of `oneof`_ ``one_filter``. - """ - - field_name: str = proto.Field( - proto.STRING, - number=1, - ) - string_filter: 'StringFilter' = proto.Field( - proto.MESSAGE, - number=4, - oneof='one_filter', - message='StringFilter', - ) - in_list_filter: 'InListFilter' = proto.Field( - proto.MESSAGE, - number=5, - oneof='one_filter', - message='InListFilter', - ) - numeric_filter: 'NumericFilter' = proto.Field( - proto.MESSAGE, - number=6, - oneof='one_filter', - message='NumericFilter', - ) - between_filter: 'BetweenFilter' = proto.Field( - proto.MESSAGE, - number=7, - oneof='one_filter', - message='BetweenFilter', - ) - - -class FunnelEventFilter(proto.Message): - r"""Creates a filter that matches events of a single event name. - If a parameter filter expression 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): - This filter matches events of this single - event name. Event name is required. - - This field is a member of `oneof`_ ``_event_name``. - funnel_parameter_filter_expression (google.analytics.data_v1alpha.types.FunnelParameterFilterExpression): - If specified, this filter matches events that - match both the single event name and the - parameter filter expressions. - Inside the parameter filter expression, only - parameter filters are available. - - This field is a member of `oneof`_ ``_funnel_parameter_filter_expression``. - """ - - event_name: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - funnel_parameter_filter_expression: 'FunnelParameterFilterExpression' = proto.Field( - proto.MESSAGE, - number=2, - optional=True, - message='FunnelParameterFilterExpression', - ) - - -class FunnelParameterFilterExpression(proto.Message): - r"""Expresses combinations of funnel filters on parameters. - - 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.data_v1alpha.types.FunnelParameterFilterExpressionList): - The FunnelParameterFilterExpression in ``andGroup`` have an - AND relationship. - - This field is a member of `oneof`_ ``expr``. - or_group (google.analytics.data_v1alpha.types.FunnelParameterFilterExpressionList): - The FunnelParameterFilterExpression in ``orGroup`` have an - OR relationship. - - This field is a member of `oneof`_ ``expr``. - not_expression (google.analytics.data_v1alpha.types.FunnelParameterFilterExpression): - The FunnelParameterFilterExpression is NOT of - ``notExpression``. - - This field is a member of `oneof`_ ``expr``. - funnel_parameter_filter (google.analytics.data_v1alpha.types.FunnelParameterFilter): - A primitive funnel parameter filter. - - This field is a member of `oneof`_ ``expr``. - """ - - and_group: 'FunnelParameterFilterExpressionList' = proto.Field( - proto.MESSAGE, - number=1, - oneof='expr', - message='FunnelParameterFilterExpressionList', - ) - or_group: 'FunnelParameterFilterExpressionList' = proto.Field( - proto.MESSAGE, - number=2, - oneof='expr', - message='FunnelParameterFilterExpressionList', - ) - not_expression: 'FunnelParameterFilterExpression' = proto.Field( - proto.MESSAGE, - number=3, - oneof='expr', - message='FunnelParameterFilterExpression', - ) - funnel_parameter_filter: 'FunnelParameterFilter' = proto.Field( - proto.MESSAGE, - number=4, - oneof='expr', - message='FunnelParameterFilter', - ) - - -class FunnelParameterFilterExpressionList(proto.Message): - r"""A list of funnel parameter filter expressions. - - Attributes: - expressions (MutableSequence[google.analytics.data_v1alpha.types.FunnelParameterFilterExpression]): - The list of funnel parameter filter - expressions. - """ - - expressions: MutableSequence['FunnelParameterFilterExpression'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='FunnelParameterFilterExpression', - ) - - -class FunnelParameterFilter(proto.Message): - r"""An expression to filter parameter values in a funnel. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - event_parameter_name (str): - This filter will be evaluated on the specified event - parameter. Event parameters are logged as parameters of the - event. Event parameters include fields like - "firebase_screen" & "currency". - - Event parameters can only be used in segments & funnels and - can only be used in a descendent filter from an EventFilter. - In a descendent filter from an EventFilter either event or - item parameters should be used. - - This field is a member of `oneof`_ ``one_parameter``. - item_parameter_name (str): - This filter will be evaluated on the specified item - parameter. Item parameters are logged as parameters in the - item array. Item parameters include fields like "item_name" - & "item_category". - - Item parameters can only be used in segments & funnels and - can only be used in a descendent filter from an EventFilter. - In a descendent filter from an EventFilter either event or - item parameters should be used. - - Item parameters are only available in ecommerce events. To - learn more about ecommerce events, see the [Measure - ecommerce] - (https://developers.google.com/analytics/devguides/collection/ga4/ecommerce) - guide. - - This field is a member of `oneof`_ ``one_parameter``. - string_filter (google.analytics.data_v1alpha.types.StringFilter): - Strings related filter. - - This field is a member of `oneof`_ ``one_filter``. - in_list_filter (google.analytics.data_v1alpha.types.InListFilter): - A filter for in list values. - - This field is a member of `oneof`_ ``one_filter``. - numeric_filter (google.analytics.data_v1alpha.types.NumericFilter): - A filter for numeric or date values. - - This field is a member of `oneof`_ ``one_filter``. - between_filter (google.analytics.data_v1alpha.types.BetweenFilter): - A filter for between two values. - - This field is a member of `oneof`_ ``one_filter``. - """ - - event_parameter_name: str = proto.Field( - proto.STRING, - number=1, - oneof='one_parameter', - ) - item_parameter_name: str = proto.Field( - proto.STRING, - number=2, - oneof='one_parameter', - ) - string_filter: 'StringFilter' = proto.Field( - proto.MESSAGE, - number=4, - oneof='one_filter', - message='StringFilter', - ) - in_list_filter: 'InListFilter' = proto.Field( - proto.MESSAGE, - number=5, - oneof='one_filter', - message='InListFilter', - ) - numeric_filter: 'NumericFilter' = proto.Field( - proto.MESSAGE, - number=6, - oneof='one_filter', - message='NumericFilter', - ) - between_filter: 'BetweenFilter' = proto.Field( - proto.MESSAGE, - number=7, - oneof='one_filter', - message='BetweenFilter', - ) - - -class FunnelResponseMetadata(proto.Message): - r"""The funnel report's response metadata carries additional - information about the funnel report. - - Attributes: - sampling_metadatas (MutableSequence[google.analytics.data_v1alpha.types.SamplingMetadata]): - If funnel report results are - `sampled `__, - this describes what percentage of events were used in this - funnel report. One ``samplingMetadatas`` is populated for - each date range. Each ``samplingMetadatas`` corresponds to a - date range in order that date ranges were specified in the - request. - - However if the results are not sampled, this field will not - be defined. - """ - - sampling_metadatas: MutableSequence['SamplingMetadata'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SamplingMetadata', - ) - - -class SamplingMetadata(proto.Message): - r"""If funnel report results are - `sampled `__, - this metadata describes what percentage of events were used in this - funnel report for a date range. Sampling is the practice of - analyzing a subset of all data in order to uncover the meaningful - information in the larger data set. - - Attributes: - samples_read_count (int): - The total number of events read in this - sampled report for a date range. This is the - size of the subset this property's data that was - analyzed in this funnel report. - sampling_space_size (int): - The total number of events present in this property's data - that could have been analyzed in this funnel report for a - date range. Sampling uncovers the meaningful information - about the larger data set, and this is the size of the - larger data set. - - To calculate the percentage of available data that was used - in this funnel report, compute - ``samplesReadCount/samplingSpaceSize``. - """ - - samples_read_count: int = proto.Field( - proto.INT64, - number=1, - ) - sampling_space_size: int = proto.Field( - proto.INT64, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/mypy.ini b/owl-bot-staging/v1alpha/mypy.ini deleted file mode 100644 index 574c5ae..0000000 --- a/owl-bot-staging/v1alpha/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/v1alpha/noxfile.py b/owl-bot-staging/v1alpha/noxfile.py deleted file mode 100644 index b15c260..0000000 --- a/owl-bot-staging/v1alpha/noxfile.py +++ /dev/null @@ -1,179 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.10" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/analytics/data_v1alpha/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.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, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_async.py deleted file mode 100644 index aa67490..0000000 --- a/owl-bot-staging/v1alpha/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RunFunnelReport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-data - - -# [START analyticsdata_v1alpha_generated_AlphaAnalyticsData_RunFunnelReport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 data_v1alpha - - -async def sample_run_funnel_report(): - # Create a client - client = data_v1alpha.AlphaAnalyticsDataAsyncClient() - - # Initialize request argument(s) - request = data_v1alpha.RunFunnelReportRequest( - ) - - # Make the request - response = await client.run_funnel_report(request=request) - - # Handle the response - print(response) - -# [END analyticsdata_v1alpha_generated_AlphaAnalyticsData_RunFunnelReport_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_sync.py deleted file mode 100644 index d65d5da..0000000 --- a/owl-bot-staging/v1alpha/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RunFunnelReport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-data - - -# [START analyticsdata_v1alpha_generated_AlphaAnalyticsData_RunFunnelReport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 data_v1alpha - - -def sample_run_funnel_report(): - # Create a client - client = data_v1alpha.AlphaAnalyticsDataClient() - - # Initialize request argument(s) - request = data_v1alpha.RunFunnelReportRequest( - ) - - # Make the request - response = client.run_funnel_report(request=request) - - # Handle the response - print(response) - -# [END analyticsdata_v1alpha_generated_AlphaAnalyticsData_RunFunnelReport_sync] diff --git a/owl-bot-staging/v1alpha/scripts/fixup_data_v1alpha_keywords.py b/owl-bot-staging/v1alpha/scripts/fixup_data_v1alpha_keywords.py deleted file mode 100644 index 8a3ca04..0000000 --- a/owl-bot-staging/v1alpha/scripts/fixup_data_v1alpha_keywords.py +++ /dev/null @@ -1,176 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 dataCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'run_funnel_report': ('property', 'date_ranges', 'funnel', 'funnel_breakdown', 'funnel_next_action', 'funnel_visualization_type', 'segments', 'limit', 'dimension_filter', 'return_property_quota', ), - } - - 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=dataCallTransformer(), -): - """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 data 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/v1alpha/setup.py b/owl-bot-staging/v1alpha/setup.py deleted file mode 100644 index 6563668..0000000 --- a/owl-bot-staging/v1alpha/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-analytics-data' - - -description = "Google Analytics Data API client library" - -version = {} -with open(os.path.join(package_root, 'google/analytics/data/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.33.2, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -url = "https://github.com/googleapis/python-google-analytics-data" - -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.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google"] -if "google.cloud" in packages: - namespaces.append("google.cloud") - -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", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/v1alpha/testing/constraints-3.10.txt b/owl-bot-staging/v1alpha/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9ae..0000000 --- a/owl-bot-staging/v1alpha/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- 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/v1alpha/testing/constraints-3.11.txt b/owl-bot-staging/v1alpha/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9ae..0000000 --- a/owl-bot-staging/v1alpha/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- 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/v1alpha/testing/constraints-3.7.txt b/owl-bot-staging/v1alpha/testing/constraints-3.7.txt deleted file mode 100644 index aca9f2d..0000000 --- a/owl-bot-staging/v1alpha/testing/constraints-3.7.txt +++ /dev/null @@ -1,11 +0,0 @@ -# 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 -# This file is intentionally left empty to test the -# latest versions of dependencies. -google-api-core==1.33.2 -proto-plus==1.22.0 -protobuf==3.19.5 diff --git a/owl-bot-staging/v1alpha/testing/constraints-3.8.txt b/owl-bot-staging/v1alpha/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9ae..0000000 --- a/owl-bot-staging/v1alpha/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- 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/v1alpha/testing/constraints-3.9.txt b/owl-bot-staging/v1alpha/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9ae..0000000 --- a/owl-bot-staging/v1alpha/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- 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/v1alpha/tests/__init__.py b/owl-bot-staging/v1alpha/tests/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1alpha/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1alpha/tests/unit/__init__.py b/owl-bot-staging/v1alpha/tests/unit/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1alpha/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1alpha/tests/unit/gapic/data_v1alpha/__init__.py b/owl-bot-staging/v1alpha/tests/unit/gapic/data_v1alpha/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1alpha/tests/unit/gapic/data_v1alpha/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1alpha/tests/unit/gapic/data_v1alpha/test_alpha_analytics_data.py b/owl-bot-staging/v1alpha/tests/unit/gapic/data_v1alpha/test_alpha_analytics_data.py deleted file mode 100644 index d0bffcc..0000000 --- a/owl-bot-staging/v1alpha/tests/unit/gapic/data_v1alpha/test_alpha_analytics_data.py +++ /dev/null @@ -1,1455 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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.data_v1alpha.services.alpha_analytics_data import AlphaAnalyticsDataAsyncClient -from google.analytics.data_v1alpha.services.alpha_analytics_data import AlphaAnalyticsDataClient -from google.analytics.data_v1alpha.services.alpha_analytics_data import transports -from google.analytics.data_v1alpha.types import analytics_data_api -from google.analytics.data_v1alpha.types import data -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert AlphaAnalyticsDataClient._get_default_mtls_endpoint(None) is None - assert AlphaAnalyticsDataClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AlphaAnalyticsDataClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AlphaAnalyticsDataClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AlphaAnalyticsDataClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AlphaAnalyticsDataClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AlphaAnalyticsDataClient, "grpc"), - (AlphaAnalyticsDataAsyncClient, "grpc_asyncio"), - (AlphaAnalyticsDataClient, "rest"), -]) -def test_alpha_analytics_data_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 == ( - 'analyticsdata.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://analyticsdata.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AlphaAnalyticsDataGrpcTransport, "grpc"), - (transports.AlphaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AlphaAnalyticsDataRestTransport, "rest"), -]) -def test_alpha_analytics_data_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", [ - (AlphaAnalyticsDataClient, "grpc"), - (AlphaAnalyticsDataAsyncClient, "grpc_asyncio"), - (AlphaAnalyticsDataClient, "rest"), -]) -def test_alpha_analytics_data_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 == ( - 'analyticsdata.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://analyticsdata.googleapis.com' - ) - - -def test_alpha_analytics_data_client_get_transport_class(): - transport = AlphaAnalyticsDataClient.get_transport_class() - available_transports = [ - transports.AlphaAnalyticsDataGrpcTransport, - transports.AlphaAnalyticsDataRestTransport, - ] - assert transport in available_transports - - transport = AlphaAnalyticsDataClient.get_transport_class("grpc") - assert transport == transports.AlphaAnalyticsDataGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataGrpcTransport, "grpc"), - (AlphaAnalyticsDataAsyncClient, transports.AlphaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio"), - (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataRestTransport, "rest"), -]) -@mock.patch.object(AlphaAnalyticsDataClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlphaAnalyticsDataClient)) -@mock.patch.object(AlphaAnalyticsDataAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlphaAnalyticsDataAsyncClient)) -def test_alpha_analytics_data_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(AlphaAnalyticsDataClient, '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(AlphaAnalyticsDataClient, '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, - 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): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # 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, - 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, - 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", [ - (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataGrpcTransport, "grpc", "true"), - (AlphaAnalyticsDataAsyncClient, transports.AlphaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataGrpcTransport, "grpc", "false"), - (AlphaAnalyticsDataAsyncClient, transports.AlphaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataRestTransport, "rest", "true"), - (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataRestTransport, "rest", "false"), -]) -@mock.patch.object(AlphaAnalyticsDataClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlphaAnalyticsDataClient)) -@mock.patch.object(AlphaAnalyticsDataAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlphaAnalyticsDataAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_alpha_analytics_data_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 - 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 - 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, - 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", [ - AlphaAnalyticsDataClient, AlphaAnalyticsDataAsyncClient -]) -@mock.patch.object(AlphaAnalyticsDataClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlphaAnalyticsDataClient)) -@mock.patch.object(AlphaAnalyticsDataAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlphaAnalyticsDataAsyncClient)) -def test_alpha_analytics_data_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 - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataGrpcTransport, "grpc"), - (AlphaAnalyticsDataAsyncClient, transports.AlphaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio"), - (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataRestTransport, "rest"), -]) -def test_alpha_analytics_data_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, - 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", [ - (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataGrpcTransport, "grpc", grpc_helpers), - (AlphaAnalyticsDataAsyncClient, transports.AlphaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataRestTransport, "rest", None), -]) -def test_alpha_analytics_data_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, - 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_alpha_analytics_data_client_client_options_from_dict(): - with mock.patch('google.analytics.data_v1alpha.services.alpha_analytics_data.transports.AlphaAnalyticsDataGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AlphaAnalyticsDataClient( - 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", [ - (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataGrpcTransport, "grpc", grpc_helpers), - (AlphaAnalyticsDataAsyncClient, transports.AlphaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_alpha_analytics_data_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, - 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( - "analyticsdata.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/analytics', - 'https://www.googleapis.com/auth/analytics.readonly', -), - scopes=None, - default_host="analyticsdata.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - analytics_data_api.RunFunnelReportRequest, - dict, -]) -def test_run_funnel_report(request_type, transport: str = 'grpc'): - client = AlphaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_funnel_report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = analytics_data_api.RunFunnelReportResponse( - kind='kind_value', - ) - response = client.run_funnel_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] == analytics_data_api.RunFunnelReportRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.RunFunnelReportResponse) - assert response.kind == 'kind_value' - - -def test_run_funnel_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 = AlphaAnalyticsDataClient( - credentials=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_funnel_report), - '__call__') as call: - client.run_funnel_report() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.RunFunnelReportRequest() - -@pytest.mark.asyncio -async def test_run_funnel_report_async(transport: str = 'grpc_asyncio', request_type=analytics_data_api.RunFunnelReportRequest): - client = AlphaAnalyticsDataAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_funnel_report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.RunFunnelReportResponse( - kind='kind_value', - )) - response = await client.run_funnel_report(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.RunFunnelReportRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.RunFunnelReportResponse) - assert response.kind == 'kind_value' - - -@pytest.mark.asyncio -async def test_run_funnel_report_async_from_dict(): - await test_run_funnel_report_async(request_type=dict) - - -def test_run_funnel_report_field_headers(): - client = AlphaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_data_api.RunFunnelReportRequest() - - request.property = 'property_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_funnel_report), - '__call__') as call: - call.return_value = analytics_data_api.RunFunnelReportResponse() - client.run_funnel_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', - 'property=property_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_run_funnel_report_field_headers_async(): - client = AlphaAnalyticsDataAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_data_api.RunFunnelReportRequest() - - request.property = 'property_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_funnel_report), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.RunFunnelReportResponse()) - await client.run_funnel_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', - 'property=property_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - analytics_data_api.RunFunnelReportRequest, - dict, -]) -def test_run_funnel_report_rest(request_type): - client = AlphaAnalyticsDataClient( - 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_data_api.RunFunnelReportResponse( - kind='kind_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = analytics_data_api.RunFunnelReportResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.run_funnel_report(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.RunFunnelReportResponse) - assert response.kind == 'kind_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_run_funnel_report_rest_interceptors(null_interceptor): - transport = transports.AlphaAnalyticsDataRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AlphaAnalyticsDataRestInterceptor(), - ) - client = AlphaAnalyticsDataClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AlphaAnalyticsDataRestInterceptor, "post_run_funnel_report") as post, \ - mock.patch.object(transports.AlphaAnalyticsDataRestInterceptor, "pre_run_funnel_report") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_data_api.RunFunnelReportRequest.pb(analytics_data_api.RunFunnelReportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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_data_api.RunFunnelReportResponse.to_json(analytics_data_api.RunFunnelReportResponse()) - - request = analytics_data_api.RunFunnelReportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = analytics_data_api.RunFunnelReportResponse() - - client.run_funnel_report(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_run_funnel_report_rest_bad_request(transport: str = 'rest', request_type=analytics_data_api.RunFunnelReportRequest): - client = AlphaAnalyticsDataClient( - 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.run_funnel_report(request) - - -def test_run_funnel_report_rest_error(): - client = AlphaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AlphaAnalyticsDataGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AlphaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AlphaAnalyticsDataGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AlphaAnalyticsDataClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AlphaAnalyticsDataGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AlphaAnalyticsDataClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AlphaAnalyticsDataClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AlphaAnalyticsDataGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AlphaAnalyticsDataClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AlphaAnalyticsDataGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AlphaAnalyticsDataClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AlphaAnalyticsDataGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AlphaAnalyticsDataGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AlphaAnalyticsDataGrpcTransport, - transports.AlphaAnalyticsDataGrpcAsyncIOTransport, - transports.AlphaAnalyticsDataRestTransport, -]) -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 = AlphaAnalyticsDataClient.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 = AlphaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AlphaAnalyticsDataGrpcTransport, - ) - -def test_alpha_analytics_data_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AlphaAnalyticsDataTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_alpha_analytics_data_base_transport(): - # Instantiate the base transport. - with mock.patch('google.analytics.data_v1alpha.services.alpha_analytics_data.transports.AlphaAnalyticsDataTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AlphaAnalyticsDataTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'run_funnel_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_alpha_analytics_data_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.data_v1alpha.services.alpha_analytics_data.transports.AlphaAnalyticsDataTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AlphaAnalyticsDataTransport( - 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', - 'https://www.googleapis.com/auth/analytics.readonly', -), - quota_project_id="octopus", - ) - - -def test_alpha_analytics_data_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.data_v1alpha.services.alpha_analytics_data.transports.AlphaAnalyticsDataTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AlphaAnalyticsDataTransport() - adc.assert_called_once() - - -def test_alpha_analytics_data_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) - AlphaAnalyticsDataClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/analytics', - 'https://www.googleapis.com/auth/analytics.readonly', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AlphaAnalyticsDataGrpcTransport, - transports.AlphaAnalyticsDataGrpcAsyncIOTransport, - ], -) -def test_alpha_analytics_data_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', 'https://www.googleapis.com/auth/analytics.readonly',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AlphaAnalyticsDataGrpcTransport, - transports.AlphaAnalyticsDataGrpcAsyncIOTransport, - transports.AlphaAnalyticsDataRestTransport, - ], -) -def test_alpha_analytics_data_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.AlphaAnalyticsDataGrpcTransport, grpc_helpers), - (transports.AlphaAnalyticsDataGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_alpha_analytics_data_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( - "analyticsdata.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/analytics', - 'https://www.googleapis.com/auth/analytics.readonly', -), - scopes=["1", "2"], - default_host="analyticsdata.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.AlphaAnalyticsDataGrpcTransport, transports.AlphaAnalyticsDataGrpcAsyncIOTransport]) -def test_alpha_analytics_data_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_alpha_analytics_data_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.AlphaAnalyticsDataRestTransport ( - 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_alpha_analytics_data_host_no_port(transport_name): - client = AlphaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='analyticsdata.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'analyticsdata.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://analyticsdata.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_alpha_analytics_data_host_with_port(transport_name): - client = AlphaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='analyticsdata.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'analyticsdata.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://analyticsdata.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_alpha_analytics_data_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AlphaAnalyticsDataClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AlphaAnalyticsDataClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.run_funnel_report._session - session2 = client2.transport.run_funnel_report._session - assert session1 != session2 -def test_alpha_analytics_data_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AlphaAnalyticsDataGrpcTransport( - 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_alpha_analytics_data_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AlphaAnalyticsDataGrpcAsyncIOTransport( - 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.AlphaAnalyticsDataGrpcTransport, transports.AlphaAnalyticsDataGrpcAsyncIOTransport]) -def test_alpha_analytics_data_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.AlphaAnalyticsDataGrpcTransport, transports.AlphaAnalyticsDataGrpcAsyncIOTransport]) -def test_alpha_analytics_data_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_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AlphaAnalyticsDataClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = AlphaAnalyticsDataClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AlphaAnalyticsDataClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = AlphaAnalyticsDataClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = AlphaAnalyticsDataClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AlphaAnalyticsDataClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AlphaAnalyticsDataClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = AlphaAnalyticsDataClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AlphaAnalyticsDataClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = AlphaAnalyticsDataClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = AlphaAnalyticsDataClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AlphaAnalyticsDataClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = AlphaAnalyticsDataClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = AlphaAnalyticsDataClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AlphaAnalyticsDataClient.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.AlphaAnalyticsDataTransport, '_prep_wrapped_messages') as prep: - client = AlphaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AlphaAnalyticsDataTransport, '_prep_wrapped_messages') as prep: - transport_class = AlphaAnalyticsDataClient.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 = AlphaAnalyticsDataAsyncClient( - 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 = AlphaAnalyticsDataClient( - 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 = AlphaAnalyticsDataClient( - 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", [ - (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataGrpcTransport), - (AlphaAnalyticsDataAsyncClient, transports.AlphaAnalyticsDataGrpcAsyncIOTransport), -]) -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, - 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/v1beta/.coveragerc b/owl-bot-staging/v1beta/.coveragerc deleted file mode 100644 index 535122d..0000000 --- a/owl-bot-staging/v1beta/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/analytics/data/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1beta/.flake8 b/owl-bot-staging/v1beta/.flake8 deleted file mode 100644 index 29227d4..0000000 --- a/owl-bot-staging/v1beta/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# 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/v1beta/MANIFEST.in b/owl-bot-staging/v1beta/MANIFEST.in deleted file mode 100644 index 910ea96..0000000 --- a/owl-bot-staging/v1beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/analytics/data *.py -recursive-include google/analytics/data_v1beta *.py diff --git a/owl-bot-staging/v1beta/README.rst b/owl-bot-staging/v1beta/README.rst deleted file mode 100644 index d62497b..0000000 --- a/owl-bot-staging/v1beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Analytics Data 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 Data 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/v1beta/docs/conf.py b/owl-bot-staging/v1beta/docs/conf.py deleted file mode 100644 index ad79bba..0000000 --- a/owl-bot-staging/v1beta/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-data 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-data" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google 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-data-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-data.tex", - u"google-analytics-data 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-data", - u"Google Analytics Data 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-data", - u"google-analytics-data Documentation", - author, - "google-analytics-data", - "GAPIC library for Google Analytics Data 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/v1beta/docs/data_v1beta/beta_analytics_data.rst b/owl-bot-staging/v1beta/docs/data_v1beta/beta_analytics_data.rst deleted file mode 100644 index 7bcaa51..0000000 --- a/owl-bot-staging/v1beta/docs/data_v1beta/beta_analytics_data.rst +++ /dev/null @@ -1,6 +0,0 @@ -BetaAnalyticsData ------------------------------------ - -.. automodule:: google.analytics.data_v1beta.services.beta_analytics_data - :members: - :inherited-members: diff --git a/owl-bot-staging/v1beta/docs/data_v1beta/services.rst b/owl-bot-staging/v1beta/docs/data_v1beta/services.rst deleted file mode 100644 index 769b3f8..0000000 --- a/owl-bot-staging/v1beta/docs/data_v1beta/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Analytics Data v1beta API -============================================= -.. toctree:: - :maxdepth: 2 - - beta_analytics_data diff --git a/owl-bot-staging/v1beta/docs/data_v1beta/types.rst b/owl-bot-staging/v1beta/docs/data_v1beta/types.rst deleted file mode 100644 index e7db7e0..0000000 --- a/owl-bot-staging/v1beta/docs/data_v1beta/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Analytics Data v1beta API -========================================== - -.. automodule:: google.analytics.data_v1beta.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1beta/docs/index.rst b/owl-bot-staging/v1beta/docs/index.rst deleted file mode 100644 index aa46cf2..0000000 --- a/owl-bot-staging/v1beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - data_v1beta/services - data_v1beta/types diff --git a/owl-bot-staging/v1beta/google/analytics/data/__init__.py b/owl-bot-staging/v1beta/google/analytics/data/__init__.py deleted file mode 100644 index 6343a3b..0000000 --- a/owl-bot-staging/v1beta/google/analytics/data/__init__.py +++ /dev/null @@ -1,121 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.data import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.analytics.data_v1beta.services.beta_analytics_data.client import BetaAnalyticsDataClient -from google.analytics.data_v1beta.services.beta_analytics_data.async_client import BetaAnalyticsDataAsyncClient - -from google.analytics.data_v1beta.types.analytics_data_api import BatchRunPivotReportsRequest -from google.analytics.data_v1beta.types.analytics_data_api import BatchRunPivotReportsResponse -from google.analytics.data_v1beta.types.analytics_data_api import BatchRunReportsRequest -from google.analytics.data_v1beta.types.analytics_data_api import BatchRunReportsResponse -from google.analytics.data_v1beta.types.analytics_data_api import CheckCompatibilityRequest -from google.analytics.data_v1beta.types.analytics_data_api import CheckCompatibilityResponse -from google.analytics.data_v1beta.types.analytics_data_api import GetMetadataRequest -from google.analytics.data_v1beta.types.analytics_data_api import Metadata -from google.analytics.data_v1beta.types.analytics_data_api import RunPivotReportRequest -from google.analytics.data_v1beta.types.analytics_data_api import RunPivotReportResponse -from google.analytics.data_v1beta.types.analytics_data_api import RunRealtimeReportRequest -from google.analytics.data_v1beta.types.analytics_data_api import RunRealtimeReportResponse -from google.analytics.data_v1beta.types.analytics_data_api import RunReportRequest -from google.analytics.data_v1beta.types.analytics_data_api import RunReportResponse -from google.analytics.data_v1beta.types.data import Cohort -from google.analytics.data_v1beta.types.data import CohortReportSettings -from google.analytics.data_v1beta.types.data import CohortSpec -from google.analytics.data_v1beta.types.data import CohortsRange -from google.analytics.data_v1beta.types.data import DateRange -from google.analytics.data_v1beta.types.data import Dimension -from google.analytics.data_v1beta.types.data import DimensionCompatibility -from google.analytics.data_v1beta.types.data import DimensionExpression -from google.analytics.data_v1beta.types.data import DimensionHeader -from google.analytics.data_v1beta.types.data import DimensionMetadata -from google.analytics.data_v1beta.types.data import DimensionValue -from google.analytics.data_v1beta.types.data import Filter -from google.analytics.data_v1beta.types.data import FilterExpression -from google.analytics.data_v1beta.types.data import FilterExpressionList -from google.analytics.data_v1beta.types.data import Metric -from google.analytics.data_v1beta.types.data import MetricCompatibility -from google.analytics.data_v1beta.types.data import MetricHeader -from google.analytics.data_v1beta.types.data import MetricMetadata -from google.analytics.data_v1beta.types.data import MetricValue -from google.analytics.data_v1beta.types.data import MinuteRange -from google.analytics.data_v1beta.types.data import NumericValue -from google.analytics.data_v1beta.types.data import OrderBy -from google.analytics.data_v1beta.types.data import Pivot -from google.analytics.data_v1beta.types.data import PivotDimensionHeader -from google.analytics.data_v1beta.types.data import PivotHeader -from google.analytics.data_v1beta.types.data import PropertyQuota -from google.analytics.data_v1beta.types.data import QuotaStatus -from google.analytics.data_v1beta.types.data import ResponseMetaData -from google.analytics.data_v1beta.types.data import Row -from google.analytics.data_v1beta.types.data import Compatibility -from google.analytics.data_v1beta.types.data import MetricAggregation -from google.analytics.data_v1beta.types.data import MetricType -from google.analytics.data_v1beta.types.data import RestrictedMetricType - -__all__ = ('BetaAnalyticsDataClient', - 'BetaAnalyticsDataAsyncClient', - 'BatchRunPivotReportsRequest', - 'BatchRunPivotReportsResponse', - 'BatchRunReportsRequest', - 'BatchRunReportsResponse', - 'CheckCompatibilityRequest', - 'CheckCompatibilityResponse', - 'GetMetadataRequest', - 'Metadata', - 'RunPivotReportRequest', - 'RunPivotReportResponse', - 'RunRealtimeReportRequest', - 'RunRealtimeReportResponse', - 'RunReportRequest', - 'RunReportResponse', - 'Cohort', - 'CohortReportSettings', - 'CohortSpec', - 'CohortsRange', - 'DateRange', - 'Dimension', - 'DimensionCompatibility', - 'DimensionExpression', - 'DimensionHeader', - 'DimensionMetadata', - 'DimensionValue', - 'Filter', - 'FilterExpression', - 'FilterExpressionList', - 'Metric', - 'MetricCompatibility', - 'MetricHeader', - 'MetricMetadata', - 'MetricValue', - 'MinuteRange', - 'NumericValue', - 'OrderBy', - 'Pivot', - 'PivotDimensionHeader', - 'PivotHeader', - 'PropertyQuota', - 'QuotaStatus', - 'ResponseMetaData', - 'Row', - 'Compatibility', - 'MetricAggregation', - 'MetricType', - 'RestrictedMetricType', -) diff --git a/owl-bot-staging/v1beta/google/analytics/data/gapic_version.py b/owl-bot-staging/v1beta/google/analytics/data/gapic_version.py deleted file mode 100644 index 35859c3..0000000 --- a/owl-bot-staging/v1beta/google/analytics/data/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.1.0" diff --git a/owl-bot-staging/v1beta/google/analytics/data/py.typed b/owl-bot-staging/v1beta/google/analytics/data/py.typed deleted file mode 100644 index 1d549e5..0000000 --- a/owl-bot-staging/v1beta/google/analytics/data/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-analytics-data package uses inline types. diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/__init__.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/__init__.py deleted file mode 100644 index ad2bbe9..0000000 --- a/owl-bot-staging/v1beta/google/analytics/data_v1beta/__init__.py +++ /dev/null @@ -1,122 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.data import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.beta_analytics_data import BetaAnalyticsDataClient -from .services.beta_analytics_data import BetaAnalyticsDataAsyncClient - -from .types.analytics_data_api import BatchRunPivotReportsRequest -from .types.analytics_data_api import BatchRunPivotReportsResponse -from .types.analytics_data_api import BatchRunReportsRequest -from .types.analytics_data_api import BatchRunReportsResponse -from .types.analytics_data_api import CheckCompatibilityRequest -from .types.analytics_data_api import CheckCompatibilityResponse -from .types.analytics_data_api import GetMetadataRequest -from .types.analytics_data_api import Metadata -from .types.analytics_data_api import RunPivotReportRequest -from .types.analytics_data_api import RunPivotReportResponse -from .types.analytics_data_api import RunRealtimeReportRequest -from .types.analytics_data_api import RunRealtimeReportResponse -from .types.analytics_data_api import RunReportRequest -from .types.analytics_data_api import RunReportResponse -from .types.data import Cohort -from .types.data import CohortReportSettings -from .types.data import CohortSpec -from .types.data import CohortsRange -from .types.data import DateRange -from .types.data import Dimension -from .types.data import DimensionCompatibility -from .types.data import DimensionExpression -from .types.data import DimensionHeader -from .types.data import DimensionMetadata -from .types.data import DimensionValue -from .types.data import Filter -from .types.data import FilterExpression -from .types.data import FilterExpressionList -from .types.data import Metric -from .types.data import MetricCompatibility -from .types.data import MetricHeader -from .types.data import MetricMetadata -from .types.data import MetricValue -from .types.data import MinuteRange -from .types.data import NumericValue -from .types.data import OrderBy -from .types.data import Pivot -from .types.data import PivotDimensionHeader -from .types.data import PivotHeader -from .types.data import PropertyQuota -from .types.data import QuotaStatus -from .types.data import ResponseMetaData -from .types.data import Row -from .types.data import Compatibility -from .types.data import MetricAggregation -from .types.data import MetricType -from .types.data import RestrictedMetricType - -__all__ = ( - 'BetaAnalyticsDataAsyncClient', -'BatchRunPivotReportsRequest', -'BatchRunPivotReportsResponse', -'BatchRunReportsRequest', -'BatchRunReportsResponse', -'BetaAnalyticsDataClient', -'CheckCompatibilityRequest', -'CheckCompatibilityResponse', -'Cohort', -'CohortReportSettings', -'CohortSpec', -'CohortsRange', -'Compatibility', -'DateRange', -'Dimension', -'DimensionCompatibility', -'DimensionExpression', -'DimensionHeader', -'DimensionMetadata', -'DimensionValue', -'Filter', -'FilterExpression', -'FilterExpressionList', -'GetMetadataRequest', -'Metadata', -'Metric', -'MetricAggregation', -'MetricCompatibility', -'MetricHeader', -'MetricMetadata', -'MetricType', -'MetricValue', -'MinuteRange', -'NumericValue', -'OrderBy', -'Pivot', -'PivotDimensionHeader', -'PivotHeader', -'PropertyQuota', -'QuotaStatus', -'ResponseMetaData', -'RestrictedMetricType', -'Row', -'RunPivotReportRequest', -'RunPivotReportResponse', -'RunRealtimeReportRequest', -'RunRealtimeReportResponse', -'RunReportRequest', -'RunReportResponse', -) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/gapic_metadata.json b/owl-bot-staging/v1beta/google/analytics/data_v1beta/gapic_metadata.json deleted file mode 100644 index e1e3750..0000000 --- a/owl-bot-staging/v1beta/google/analytics/data_v1beta/gapic_metadata.json +++ /dev/null @@ -1,133 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.analytics.data_v1beta", - "protoPackage": "google.analytics.data.v1beta", - "schema": "1.0", - "services": { - "BetaAnalyticsData": { - "clients": { - "grpc": { - "libraryClient": "BetaAnalyticsDataClient", - "rpcs": { - "BatchRunPivotReports": { - "methods": [ - "batch_run_pivot_reports" - ] - }, - "BatchRunReports": { - "methods": [ - "batch_run_reports" - ] - }, - "CheckCompatibility": { - "methods": [ - "check_compatibility" - ] - }, - "GetMetadata": { - "methods": [ - "get_metadata" - ] - }, - "RunPivotReport": { - "methods": [ - "run_pivot_report" - ] - }, - "RunRealtimeReport": { - "methods": [ - "run_realtime_report" - ] - }, - "RunReport": { - "methods": [ - "run_report" - ] - } - } - }, - "grpc-async": { - "libraryClient": "BetaAnalyticsDataAsyncClient", - "rpcs": { - "BatchRunPivotReports": { - "methods": [ - "batch_run_pivot_reports" - ] - }, - "BatchRunReports": { - "methods": [ - "batch_run_reports" - ] - }, - "CheckCompatibility": { - "methods": [ - "check_compatibility" - ] - }, - "GetMetadata": { - "methods": [ - "get_metadata" - ] - }, - "RunPivotReport": { - "methods": [ - "run_pivot_report" - ] - }, - "RunRealtimeReport": { - "methods": [ - "run_realtime_report" - ] - }, - "RunReport": { - "methods": [ - "run_report" - ] - } - } - }, - "rest": { - "libraryClient": "BetaAnalyticsDataClient", - "rpcs": { - "BatchRunPivotReports": { - "methods": [ - "batch_run_pivot_reports" - ] - }, - "BatchRunReports": { - "methods": [ - "batch_run_reports" - ] - }, - "CheckCompatibility": { - "methods": [ - "check_compatibility" - ] - }, - "GetMetadata": { - "methods": [ - "get_metadata" - ] - }, - "RunPivotReport": { - "methods": [ - "run_pivot_report" - ] - }, - "RunRealtimeReport": { - "methods": [ - "run_realtime_report" - ] - }, - "RunReport": { - "methods": [ - "run_report" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/py.typed b/owl-bot-staging/v1beta/google/analytics/data_v1beta/py.typed deleted file mode 100644 index 1d549e5..0000000 --- a/owl-bot-staging/v1beta/google/analytics/data_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-analytics-data package uses inline types. diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/__init__.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/__init__.py deleted file mode 100644 index e8e1c38..0000000 --- a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/__init__.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/__init__.py deleted file mode 100644 index da34317..0000000 --- a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 BetaAnalyticsDataClient -from .async_client import BetaAnalyticsDataAsyncClient - -__all__ = ( - 'BetaAnalyticsDataClient', - 'BetaAnalyticsDataAsyncClient', -) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/async_client.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/async_client.py deleted file mode 100644 index 287b324..0000000 --- a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/async_client.py +++ /dev/null @@ -1,846 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.analytics.data_v1beta.types import analytics_data_api -from google.analytics.data_v1beta.types import data -from .transports.base import BetaAnalyticsDataTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import BetaAnalyticsDataGrpcAsyncIOTransport -from .client import BetaAnalyticsDataClient - - -class BetaAnalyticsDataAsyncClient: - """Google Analytics reporting data service.""" - - _client: BetaAnalyticsDataClient - - DEFAULT_ENDPOINT = BetaAnalyticsDataClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = BetaAnalyticsDataClient.DEFAULT_MTLS_ENDPOINT - - metadata_path = staticmethod(BetaAnalyticsDataClient.metadata_path) - parse_metadata_path = staticmethod(BetaAnalyticsDataClient.parse_metadata_path) - common_billing_account_path = staticmethod(BetaAnalyticsDataClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(BetaAnalyticsDataClient.parse_common_billing_account_path) - common_folder_path = staticmethod(BetaAnalyticsDataClient.common_folder_path) - parse_common_folder_path = staticmethod(BetaAnalyticsDataClient.parse_common_folder_path) - common_organization_path = staticmethod(BetaAnalyticsDataClient.common_organization_path) - parse_common_organization_path = staticmethod(BetaAnalyticsDataClient.parse_common_organization_path) - common_project_path = staticmethod(BetaAnalyticsDataClient.common_project_path) - parse_common_project_path = staticmethod(BetaAnalyticsDataClient.parse_common_project_path) - common_location_path = staticmethod(BetaAnalyticsDataClient.common_location_path) - parse_common_location_path = staticmethod(BetaAnalyticsDataClient.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: - BetaAnalyticsDataAsyncClient: The constructed client. - """ - return BetaAnalyticsDataClient.from_service_account_info.__func__(BetaAnalyticsDataAsyncClient, 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: - BetaAnalyticsDataAsyncClient: The constructed client. - """ - return BetaAnalyticsDataClient.from_service_account_file.__func__(BetaAnalyticsDataAsyncClient, 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 variabel 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 BetaAnalyticsDataClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> BetaAnalyticsDataTransport: - """Returns the transport used by the client instance. - - Returns: - BetaAnalyticsDataTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(BetaAnalyticsDataClient).get_transport_class, type(BetaAnalyticsDataClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, BetaAnalyticsDataTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the beta analytics data client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.BetaAnalyticsDataTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = BetaAnalyticsDataClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def run_report(self, - request: Optional[Union[analytics_data_api.RunReportRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.RunReportResponse: - r"""Returns a customized report of your Google Analytics event data. - Reports contain statistics derived from data collected by the - Google Analytics tracking code. The data returned from the API - is as a table with columns for the requested dimensions and - metrics. Metrics are individual measurements of user activity on - your property, such as active users or event count. Dimensions - break down metrics across some common criteria, such as country - or event name. - - For a guide to constructing requests & understanding responses, - see `Creating a - Report `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 data_v1beta - - async def sample_run_report(): - # Create a client - client = data_v1beta.BetaAnalyticsDataAsyncClient() - - # Initialize request argument(s) - request = data_v1beta.RunReportRequest( - ) - - # Make the request - response = await client.run_report(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.analytics.data_v1beta.types.RunReportRequest, dict]]): - The request object. The request to generate a 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.data_v1beta.types.RunReportResponse: - The response report table - corresponding to a request. - - """ - # Create or coerce a protobuf request object. - request = analytics_data_api.RunReportRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.run_report, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("property", request.property), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def run_pivot_report(self, - request: Optional[Union[analytics_data_api.RunPivotReportRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.RunPivotReportResponse: - r"""Returns a customized pivot report of your Google - Analytics event data. Pivot reports are more advanced - and expressive formats than regular reports. In a pivot - report, dimensions are only visible if they are included - in a pivot. Multiple pivots can be specified to further - dissect your data. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.analytics import data_v1beta - - async def sample_run_pivot_report(): - # Create a client - client = data_v1beta.BetaAnalyticsDataAsyncClient() - - # Initialize request argument(s) - request = data_v1beta.RunPivotReportRequest( - ) - - # Make the request - response = await client.run_pivot_report(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.analytics.data_v1beta.types.RunPivotReportRequest, dict]]): - The request object. The request to generate a pivot - 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.data_v1beta.types.RunPivotReportResponse: - The response pivot report table - corresponding to a pivot request. - - """ - # Create or coerce a protobuf request object. - request = analytics_data_api.RunPivotReportRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.run_pivot_report, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("property", request.property), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def batch_run_reports(self, - request: Optional[Union[analytics_data_api.BatchRunReportsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.BatchRunReportsResponse: - r"""Returns multiple reports in a batch. All reports must - be for the same 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 data_v1beta - - async def sample_batch_run_reports(): - # Create a client - client = data_v1beta.BetaAnalyticsDataAsyncClient() - - # Initialize request argument(s) - request = data_v1beta.BatchRunReportsRequest( - ) - - # Make the request - response = await client.batch_run_reports(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.analytics.data_v1beta.types.BatchRunReportsRequest, dict]]): - The request object. The batch request containing - multiple report requests. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.analytics.data_v1beta.types.BatchRunReportsResponse: - The batch response containing - multiple reports. - - """ - # Create or coerce a protobuf request object. - request = analytics_data_api.BatchRunReportsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_run_reports, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("property", request.property), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def batch_run_pivot_reports(self, - request: Optional[Union[analytics_data_api.BatchRunPivotReportsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.BatchRunPivotReportsResponse: - r"""Returns multiple pivot reports in a batch. All - reports must be for the same 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 data_v1beta - - async def sample_batch_run_pivot_reports(): - # Create a client - client = data_v1beta.BetaAnalyticsDataAsyncClient() - - # Initialize request argument(s) - request = data_v1beta.BatchRunPivotReportsRequest( - ) - - # Make the request - response = await client.batch_run_pivot_reports(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.analytics.data_v1beta.types.BatchRunPivotReportsRequest, dict]]): - The request object. The batch request containing - multiple pivot report requests. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.analytics.data_v1beta.types.BatchRunPivotReportsResponse: - The batch response containing - multiple pivot reports. - - """ - # Create or coerce a protobuf request object. - request = analytics_data_api.BatchRunPivotReportsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_run_pivot_reports, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("property", request.property), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_metadata(self, - request: Optional[Union[analytics_data_api.GetMetadataRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.Metadata: - r"""Returns metadata for dimensions and metrics available in - reporting methods. Used to explore the dimensions and metrics. - In this method, a Google Analytics GA4 Property Identifier is - specified in the request, and the metadata response includes - Custom dimensions and metrics as well as Universal metadata. - - For example if a custom metric with parameter name - ``levels_unlocked`` is registered to a property, the Metadata - response will contain ``customEvent:levels_unlocked``. Universal - metadata are dimensions and metrics applicable to any property - such as ``country`` and ``totalUsers``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 data_v1beta - - async def sample_get_metadata(): - # Create a client - client = data_v1beta.BetaAnalyticsDataAsyncClient() - - # Initialize request argument(s) - request = data_v1beta.GetMetadataRequest( - name="name_value", - ) - - # Make the request - response = await client.get_metadata(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.analytics.data_v1beta.types.GetMetadataRequest, dict]]): - The request object. Request for a property's dimension - and metric metadata. - name (:class:`str`): - Required. The resource name of the metadata to retrieve. - This name field is specified in the URL path and not URL - parameters. Property is a numeric Google Analytics GA4 - Property identifier. To learn more, see `where to find - your Property - ID `__. - - Example: properties/1234/metadata - - Set the Property ID to 0 for dimensions and metrics - common to all properties. In this special mode, this - method will not return custom dimensions and metrics. - - 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.data_v1beta.types.Metadata: - The dimensions and metrics currently - accepted in reporting methods. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = analytics_data_api.GetMetadataRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_metadata, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def run_realtime_report(self, - request: Optional[Union[analytics_data_api.RunRealtimeReportRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.RunRealtimeReportResponse: - r"""Returns a customized report of realtime event data for your - property. Events appear in realtime reports seconds after they - have been sent to the Google Analytics. Realtime reports show - events and usage data for the periods of time ranging from the - present moment to 30 minutes ago (up to 60 minutes for Google - Analytics 360 properties). - - For a guide to constructing realtime requests & understanding - responses, see `Creating a Realtime - Report `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 data_v1beta - - async def sample_run_realtime_report(): - # Create a client - client = data_v1beta.BetaAnalyticsDataAsyncClient() - - # Initialize request argument(s) - request = data_v1beta.RunRealtimeReportRequest( - ) - - # Make the request - response = await client.run_realtime_report(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.analytics.data_v1beta.types.RunRealtimeReportRequest, dict]]): - The request object. The request to generate a realtime - 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.data_v1beta.types.RunRealtimeReportResponse: - The response realtime report table - corresponding to a request. - - """ - # Create or coerce a protobuf request object. - request = analytics_data_api.RunRealtimeReportRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.run_realtime_report, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("property", request.property), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def check_compatibility(self, - request: Optional[Union[analytics_data_api.CheckCompatibilityRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.CheckCompatibilityResponse: - r"""This compatibility method lists dimensions and - metrics that can be added to a report request and - maintain compatibility. This method fails if the - request's dimensions and metrics are incompatible. - In Google Analytics, reports fail if they request - incompatible dimensions and/or metrics; in that case, - you will need to remove dimensions and/or metrics from - the incompatible report until the report is compatible. - The Realtime and Core reports have different - compatibility rules. This method checks compatibility - for Core reports. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 data_v1beta - - async def sample_check_compatibility(): - # Create a client - client = data_v1beta.BetaAnalyticsDataAsyncClient() - - # Initialize request argument(s) - request = data_v1beta.CheckCompatibilityRequest( - ) - - # Make the request - response = await client.check_compatibility(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.analytics.data_v1beta.types.CheckCompatibilityRequest, dict]]): - The request object. The request for compatibility - information for a report's dimensions and metrics. Check - compatibility provides a preview of the compatibility of - a report; fields shared with the `runReport` request - should be the same values as in your `runReport` - request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.analytics.data_v1beta.types.CheckCompatibilityResponse: - The compatibility response with the - compatibility of each dimension & - metric. - - """ - # Create or coerce a protobuf request object. - request = analytics_data_api.CheckCompatibilityRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.check_compatibility, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("property", request.property), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-analytics-data", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "BetaAnalyticsDataAsyncClient", -) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/client.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/client.py deleted file mode 100644 index 233a1b8..0000000 --- a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/client.py +++ /dev/null @@ -1,1058 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import pkg_resources - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.analytics.data_v1beta.types import analytics_data_api -from google.analytics.data_v1beta.types import data -from .transports.base import BetaAnalyticsDataTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import BetaAnalyticsDataGrpcTransport -from .transports.grpc_asyncio import BetaAnalyticsDataGrpcAsyncIOTransport -from .transports.rest import BetaAnalyticsDataRestTransport - - -class BetaAnalyticsDataClientMeta(type): - """Metaclass for the BetaAnalyticsData 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[BetaAnalyticsDataTransport]] - _transport_registry["grpc"] = BetaAnalyticsDataGrpcTransport - _transport_registry["grpc_asyncio"] = BetaAnalyticsDataGrpcAsyncIOTransport - _transport_registry["rest"] = BetaAnalyticsDataRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[BetaAnalyticsDataTransport]: - """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 BetaAnalyticsDataClient(metaclass=BetaAnalyticsDataClientMeta): - """Google Analytics reporting data service.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "analyticsdata.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - BetaAnalyticsDataClient: 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: - BetaAnalyticsDataClient: 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) -> BetaAnalyticsDataTransport: - """Returns the transport used by the client instance. - - Returns: - BetaAnalyticsDataTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def metadata_path(property: str,) -> str: - """Returns a fully-qualified metadata string.""" - return "properties/{property}/metadata".format(property=property, ) - - @staticmethod - def parse_metadata_path(path: str) -> Dict[str,str]: - """Parses a metadata path into its component segments.""" - m = re.match(r"^properties/(?P.+?)/metadata$", 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): - """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 variabel 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. - """ - 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 - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, BetaAnalyticsDataTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the beta analytics data client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, BetaAnalyticsDataTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - NOTE: "rest" transport functionality is currently in a - beta state (preview). We welcome your feedback via an - issue in this library's source repository. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(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. - if isinstance(transport, BetaAnalyticsDataTransport): - # transport is a BetaAnalyticsDataTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def run_report(self, - request: Optional[Union[analytics_data_api.RunReportRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.RunReportResponse: - r"""Returns a customized report of your Google Analytics event data. - Reports contain statistics derived from data collected by the - Google Analytics tracking code. The data returned from the API - is as a table with columns for the requested dimensions and - metrics. Metrics are individual measurements of user activity on - your property, such as active users or event count. Dimensions - break down metrics across some common criteria, such as country - or event name. - - For a guide to constructing requests & understanding responses, - see `Creating a - Report `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 data_v1beta - - def sample_run_report(): - # Create a client - client = data_v1beta.BetaAnalyticsDataClient() - - # Initialize request argument(s) - request = data_v1beta.RunReportRequest( - ) - - # Make the request - response = client.run_report(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.analytics.data_v1beta.types.RunReportRequest, dict]): - The request object. The request to generate a 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.data_v1beta.types.RunReportResponse: - The response report table - corresponding to a request. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a analytics_data_api.RunReportRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, analytics_data_api.RunReportRequest): - request = analytics_data_api.RunReportRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.run_report] - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def run_pivot_report(self, - request: Optional[Union[analytics_data_api.RunPivotReportRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.RunPivotReportResponse: - r"""Returns a customized pivot report of your Google - Analytics event data. Pivot reports are more advanced - and expressive formats than regular reports. In a pivot - report, dimensions are only visible if they are included - in a pivot. Multiple pivots can be specified to further - dissect your data. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.analytics import data_v1beta - - def sample_run_pivot_report(): - # Create a client - client = data_v1beta.BetaAnalyticsDataClient() - - # Initialize request argument(s) - request = data_v1beta.RunPivotReportRequest( - ) - - # Make the request - response = client.run_pivot_report(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.analytics.data_v1beta.types.RunPivotReportRequest, dict]): - The request object. The request to generate a pivot - 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.data_v1beta.types.RunPivotReportResponse: - The response pivot report table - corresponding to a pivot request. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a analytics_data_api.RunPivotReportRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, analytics_data_api.RunPivotReportRequest): - request = analytics_data_api.RunPivotReportRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.run_pivot_report] - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def batch_run_reports(self, - request: Optional[Union[analytics_data_api.BatchRunReportsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.BatchRunReportsResponse: - r"""Returns multiple reports in a batch. All reports must - be for the same 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 data_v1beta - - def sample_batch_run_reports(): - # Create a client - client = data_v1beta.BetaAnalyticsDataClient() - - # Initialize request argument(s) - request = data_v1beta.BatchRunReportsRequest( - ) - - # Make the request - response = client.batch_run_reports(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.analytics.data_v1beta.types.BatchRunReportsRequest, dict]): - The request object. The batch request containing - multiple report requests. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.analytics.data_v1beta.types.BatchRunReportsResponse: - The batch response containing - multiple reports. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a analytics_data_api.BatchRunReportsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, analytics_data_api.BatchRunReportsRequest): - request = analytics_data_api.BatchRunReportsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_run_reports] - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def batch_run_pivot_reports(self, - request: Optional[Union[analytics_data_api.BatchRunPivotReportsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.BatchRunPivotReportsResponse: - r"""Returns multiple pivot reports in a batch. All - reports must be for the same 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 data_v1beta - - def sample_batch_run_pivot_reports(): - # Create a client - client = data_v1beta.BetaAnalyticsDataClient() - - # Initialize request argument(s) - request = data_v1beta.BatchRunPivotReportsRequest( - ) - - # Make the request - response = client.batch_run_pivot_reports(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.analytics.data_v1beta.types.BatchRunPivotReportsRequest, dict]): - The request object. The batch request containing - multiple pivot report requests. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.analytics.data_v1beta.types.BatchRunPivotReportsResponse: - The batch response containing - multiple pivot reports. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a analytics_data_api.BatchRunPivotReportsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, analytics_data_api.BatchRunPivotReportsRequest): - request = analytics_data_api.BatchRunPivotReportsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_run_pivot_reports] - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_metadata(self, - request: Optional[Union[analytics_data_api.GetMetadataRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.Metadata: - r"""Returns metadata for dimensions and metrics available in - reporting methods. Used to explore the dimensions and metrics. - In this method, a Google Analytics GA4 Property Identifier is - specified in the request, and the metadata response includes - Custom dimensions and metrics as well as Universal metadata. - - For example if a custom metric with parameter name - ``levels_unlocked`` is registered to a property, the Metadata - response will contain ``customEvent:levels_unlocked``. Universal - metadata are dimensions and metrics applicable to any property - such as ``country`` and ``totalUsers``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 data_v1beta - - def sample_get_metadata(): - # Create a client - client = data_v1beta.BetaAnalyticsDataClient() - - # Initialize request argument(s) - request = data_v1beta.GetMetadataRequest( - name="name_value", - ) - - # Make the request - response = client.get_metadata(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.analytics.data_v1beta.types.GetMetadataRequest, dict]): - The request object. Request for a property's dimension - and metric metadata. - name (str): - Required. The resource name of the metadata to retrieve. - This name field is specified in the URL path and not URL - parameters. Property is a numeric Google Analytics GA4 - Property identifier. To learn more, see `where to find - your Property - ID `__. - - Example: properties/1234/metadata - - Set the Property ID to 0 for dimensions and metrics - common to all properties. In this special mode, this - method will not return custom dimensions and metrics. - - 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.data_v1beta.types.Metadata: - The dimensions and metrics currently - accepted in reporting methods. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a analytics_data_api.GetMetadataRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, analytics_data_api.GetMetadataRequest): - request = analytics_data_api.GetMetadataRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_metadata] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def run_realtime_report(self, - request: Optional[Union[analytics_data_api.RunRealtimeReportRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.RunRealtimeReportResponse: - r"""Returns a customized report of realtime event data for your - property. Events appear in realtime reports seconds after they - have been sent to the Google Analytics. Realtime reports show - events and usage data for the periods of time ranging from the - present moment to 30 minutes ago (up to 60 minutes for Google - Analytics 360 properties). - - For a guide to constructing realtime requests & understanding - responses, see `Creating a Realtime - Report `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 data_v1beta - - def sample_run_realtime_report(): - # Create a client - client = data_v1beta.BetaAnalyticsDataClient() - - # Initialize request argument(s) - request = data_v1beta.RunRealtimeReportRequest( - ) - - # Make the request - response = client.run_realtime_report(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.analytics.data_v1beta.types.RunRealtimeReportRequest, dict]): - The request object. The request to generate a realtime - 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.data_v1beta.types.RunRealtimeReportResponse: - The response realtime report table - corresponding to a request. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a analytics_data_api.RunRealtimeReportRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, analytics_data_api.RunRealtimeReportRequest): - request = analytics_data_api.RunRealtimeReportRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.run_realtime_report] - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def check_compatibility(self, - request: Optional[Union[analytics_data_api.CheckCompatibilityRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.CheckCompatibilityResponse: - r"""This compatibility method lists dimensions and - metrics that can be added to a report request and - maintain compatibility. This method fails if the - request's dimensions and metrics are incompatible. - In Google Analytics, reports fail if they request - incompatible dimensions and/or metrics; in that case, - you will need to remove dimensions and/or metrics from - the incompatible report until the report is compatible. - The Realtime and Core reports have different - compatibility rules. This method checks compatibility - for Core reports. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 data_v1beta - - def sample_check_compatibility(): - # Create a client - client = data_v1beta.BetaAnalyticsDataClient() - - # Initialize request argument(s) - request = data_v1beta.CheckCompatibilityRequest( - ) - - # Make the request - response = client.check_compatibility(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.analytics.data_v1beta.types.CheckCompatibilityRequest, dict]): - The request object. The request for compatibility - information for a report's dimensions and metrics. Check - compatibility provides a preview of the compatibility of - a report; fields shared with the `runReport` request - should be the same values as in your `runReport` - request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.analytics.data_v1beta.types.CheckCompatibilityResponse: - The compatibility response with the - compatibility of each dimension & - metric. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a analytics_data_api.CheckCompatibilityRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, analytics_data_api.CheckCompatibilityRequest): - request = analytics_data_api.CheckCompatibilityRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.check_compatibility] - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-analytics-data", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "BetaAnalyticsDataClient", -) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/__init__.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/__init__.py deleted file mode 100644 index 6a1730d..0000000 --- a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 BetaAnalyticsDataTransport -from .grpc import BetaAnalyticsDataGrpcTransport -from .grpc_asyncio import BetaAnalyticsDataGrpcAsyncIOTransport -from .rest import BetaAnalyticsDataRestTransport -from .rest import BetaAnalyticsDataRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[BetaAnalyticsDataTransport]] -_transport_registry['grpc'] = BetaAnalyticsDataGrpcTransport -_transport_registry['grpc_asyncio'] = BetaAnalyticsDataGrpcAsyncIOTransport -_transport_registry['rest'] = BetaAnalyticsDataRestTransport - -__all__ = ( - 'BetaAnalyticsDataTransport', - 'BetaAnalyticsDataGrpcTransport', - 'BetaAnalyticsDataGrpcAsyncIOTransport', - 'BetaAnalyticsDataRestTransport', - 'BetaAnalyticsDataRestInterceptor', -) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/base.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/base.py deleted file mode 100644 index d158e88..0000000 --- a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/base.py +++ /dev/null @@ -1,239 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.analytics.data_v1beta.types import analytics_data_api - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-analytics-data', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class BetaAnalyticsDataTransport(abc.ABC): - """Abstract transport class for BetaAnalyticsData.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/analytics', - 'https://www.googleapis.com/auth/analytics.readonly', - ) - - DEFAULT_HOST: str = 'analyticsdata.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. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.run_report: gapic_v1.method.wrap_method( - self.run_report, - default_timeout=60.0, - client_info=client_info, - ), - self.run_pivot_report: gapic_v1.method.wrap_method( - self.run_pivot_report, - default_timeout=60.0, - client_info=client_info, - ), - self.batch_run_reports: gapic_v1.method.wrap_method( - self.batch_run_reports, - default_timeout=60.0, - client_info=client_info, - ), - self.batch_run_pivot_reports: gapic_v1.method.wrap_method( - self.batch_run_pivot_reports, - default_timeout=60.0, - client_info=client_info, - ), - self.get_metadata: gapic_v1.method.wrap_method( - self.get_metadata, - default_timeout=60.0, - client_info=client_info, - ), - self.run_realtime_report: gapic_v1.method.wrap_method( - self.run_realtime_report, - default_timeout=60.0, - client_info=client_info, - ), - self.check_compatibility: gapic_v1.method.wrap_method( - self.check_compatibility, - default_timeout=60.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def run_report(self) -> Callable[ - [analytics_data_api.RunReportRequest], - Union[ - analytics_data_api.RunReportResponse, - Awaitable[analytics_data_api.RunReportResponse] - ]]: - raise NotImplementedError() - - @property - def run_pivot_report(self) -> Callable[ - [analytics_data_api.RunPivotReportRequest], - Union[ - analytics_data_api.RunPivotReportResponse, - Awaitable[analytics_data_api.RunPivotReportResponse] - ]]: - raise NotImplementedError() - - @property - def batch_run_reports(self) -> Callable[ - [analytics_data_api.BatchRunReportsRequest], - Union[ - analytics_data_api.BatchRunReportsResponse, - Awaitable[analytics_data_api.BatchRunReportsResponse] - ]]: - raise NotImplementedError() - - @property - def batch_run_pivot_reports(self) -> Callable[ - [analytics_data_api.BatchRunPivotReportsRequest], - Union[ - analytics_data_api.BatchRunPivotReportsResponse, - Awaitable[analytics_data_api.BatchRunPivotReportsResponse] - ]]: - raise NotImplementedError() - - @property - def get_metadata(self) -> Callable[ - [analytics_data_api.GetMetadataRequest], - Union[ - analytics_data_api.Metadata, - Awaitable[analytics_data_api.Metadata] - ]]: - raise NotImplementedError() - - @property - def run_realtime_report(self) -> Callable[ - [analytics_data_api.RunRealtimeReportRequest], - Union[ - analytics_data_api.RunRealtimeReportResponse, - Awaitable[analytics_data_api.RunRealtimeReportResponse] - ]]: - raise NotImplementedError() - - @property - def check_compatibility(self) -> Callable[ - [analytics_data_api.CheckCompatibilityRequest], - Union[ - analytics_data_api.CheckCompatibilityResponse, - Awaitable[analytics_data_api.CheckCompatibilityResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'BetaAnalyticsDataTransport', -) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc.py deleted file mode 100644 index 64eb0db..0000000 --- a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc.py +++ /dev/null @@ -1,467 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.data_v1beta.types import analytics_data_api -from .base import BetaAnalyticsDataTransport, DEFAULT_CLIENT_INFO - - -class BetaAnalyticsDataGrpcTransport(BetaAnalyticsDataTransport): - """gRPC backend transport for BetaAnalyticsData. - - Google Analytics reporting data service. - - 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 = 'analyticsdata.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'analyticsdata.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 run_report(self) -> Callable[ - [analytics_data_api.RunReportRequest], - analytics_data_api.RunReportResponse]: - r"""Return a callable for the run report method over gRPC. - - Returns a customized report of your Google Analytics event data. - Reports contain statistics derived from data collected by the - Google Analytics tracking code. The data returned from the API - is as a table with columns for the requested dimensions and - metrics. Metrics are individual measurements of user activity on - your property, such as active users or event count. Dimensions - break down metrics across some common criteria, such as country - or event name. - - For a guide to constructing requests & understanding responses, - see `Creating a - Report `__. - - Returns: - Callable[[~.RunReportRequest], - ~.RunReportResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_report' not in self._stubs: - self._stubs['run_report'] = self.grpc_channel.unary_unary( - '/google.analytics.data.v1beta.BetaAnalyticsData/RunReport', - request_serializer=analytics_data_api.RunReportRequest.serialize, - response_deserializer=analytics_data_api.RunReportResponse.deserialize, - ) - return self._stubs['run_report'] - - @property - def run_pivot_report(self) -> Callable[ - [analytics_data_api.RunPivotReportRequest], - analytics_data_api.RunPivotReportResponse]: - r"""Return a callable for the run pivot report method over gRPC. - - Returns a customized pivot report of your Google - Analytics event data. Pivot reports are more advanced - and expressive formats than regular reports. In a pivot - report, dimensions are only visible if they are included - in a pivot. Multiple pivots can be specified to further - dissect your data. - - Returns: - Callable[[~.RunPivotReportRequest], - ~.RunPivotReportResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_pivot_report' not in self._stubs: - self._stubs['run_pivot_report'] = self.grpc_channel.unary_unary( - '/google.analytics.data.v1beta.BetaAnalyticsData/RunPivotReport', - request_serializer=analytics_data_api.RunPivotReportRequest.serialize, - response_deserializer=analytics_data_api.RunPivotReportResponse.deserialize, - ) - return self._stubs['run_pivot_report'] - - @property - def batch_run_reports(self) -> Callable[ - [analytics_data_api.BatchRunReportsRequest], - analytics_data_api.BatchRunReportsResponse]: - r"""Return a callable for the batch run reports method over gRPC. - - Returns multiple reports in a batch. All reports must - be for the same GA4 Property. - - Returns: - Callable[[~.BatchRunReportsRequest], - ~.BatchRunReportsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_run_reports' not in self._stubs: - self._stubs['batch_run_reports'] = self.grpc_channel.unary_unary( - '/google.analytics.data.v1beta.BetaAnalyticsData/BatchRunReports', - request_serializer=analytics_data_api.BatchRunReportsRequest.serialize, - response_deserializer=analytics_data_api.BatchRunReportsResponse.deserialize, - ) - return self._stubs['batch_run_reports'] - - @property - def batch_run_pivot_reports(self) -> Callable[ - [analytics_data_api.BatchRunPivotReportsRequest], - analytics_data_api.BatchRunPivotReportsResponse]: - r"""Return a callable for the batch run pivot reports method over gRPC. - - Returns multiple pivot reports in a batch. All - reports must be for the same GA4 Property. - - Returns: - Callable[[~.BatchRunPivotReportsRequest], - ~.BatchRunPivotReportsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_run_pivot_reports' not in self._stubs: - self._stubs['batch_run_pivot_reports'] = self.grpc_channel.unary_unary( - '/google.analytics.data.v1beta.BetaAnalyticsData/BatchRunPivotReports', - request_serializer=analytics_data_api.BatchRunPivotReportsRequest.serialize, - response_deserializer=analytics_data_api.BatchRunPivotReportsResponse.deserialize, - ) - return self._stubs['batch_run_pivot_reports'] - - @property - def get_metadata(self) -> Callable[ - [analytics_data_api.GetMetadataRequest], - analytics_data_api.Metadata]: - r"""Return a callable for the get metadata method over gRPC. - - Returns metadata for dimensions and metrics available in - reporting methods. Used to explore the dimensions and metrics. - In this method, a Google Analytics GA4 Property Identifier is - specified in the request, and the metadata response includes - Custom dimensions and metrics as well as Universal metadata. - - For example if a custom metric with parameter name - ``levels_unlocked`` is registered to a property, the Metadata - response will contain ``customEvent:levels_unlocked``. Universal - metadata are dimensions and metrics applicable to any property - such as ``country`` and ``totalUsers``. - - Returns: - Callable[[~.GetMetadataRequest], - ~.Metadata]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_metadata' not in self._stubs: - self._stubs['get_metadata'] = self.grpc_channel.unary_unary( - '/google.analytics.data.v1beta.BetaAnalyticsData/GetMetadata', - request_serializer=analytics_data_api.GetMetadataRequest.serialize, - response_deserializer=analytics_data_api.Metadata.deserialize, - ) - return self._stubs['get_metadata'] - - @property - def run_realtime_report(self) -> Callable[ - [analytics_data_api.RunRealtimeReportRequest], - analytics_data_api.RunRealtimeReportResponse]: - r"""Return a callable for the run realtime report method over gRPC. - - Returns a customized report of realtime event data for your - property. Events appear in realtime reports seconds after they - have been sent to the Google Analytics. Realtime reports show - events and usage data for the periods of time ranging from the - present moment to 30 minutes ago (up to 60 minutes for Google - Analytics 360 properties). - - For a guide to constructing realtime requests & understanding - responses, see `Creating a Realtime - Report `__. - - Returns: - Callable[[~.RunRealtimeReportRequest], - ~.RunRealtimeReportResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_realtime_report' not in self._stubs: - self._stubs['run_realtime_report'] = self.grpc_channel.unary_unary( - '/google.analytics.data.v1beta.BetaAnalyticsData/RunRealtimeReport', - request_serializer=analytics_data_api.RunRealtimeReportRequest.serialize, - response_deserializer=analytics_data_api.RunRealtimeReportResponse.deserialize, - ) - return self._stubs['run_realtime_report'] - - @property - def check_compatibility(self) -> Callable[ - [analytics_data_api.CheckCompatibilityRequest], - analytics_data_api.CheckCompatibilityResponse]: - r"""Return a callable for the check compatibility method over gRPC. - - This compatibility method lists dimensions and - metrics that can be added to a report request and - maintain compatibility. This method fails if the - request's dimensions and metrics are incompatible. - In Google Analytics, reports fail if they request - incompatible dimensions and/or metrics; in that case, - you will need to remove dimensions and/or metrics from - the incompatible report until the report is compatible. - The Realtime and Core reports have different - compatibility rules. This method checks compatibility - for Core reports. - - Returns: - Callable[[~.CheckCompatibilityRequest], - ~.CheckCompatibilityResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'check_compatibility' not in self._stubs: - self._stubs['check_compatibility'] = self.grpc_channel.unary_unary( - '/google.analytics.data.v1beta.BetaAnalyticsData/CheckCompatibility', - request_serializer=analytics_data_api.CheckCompatibilityRequest.serialize, - response_deserializer=analytics_data_api.CheckCompatibilityResponse.deserialize, - ) - return self._stubs['check_compatibility'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'BetaAnalyticsDataGrpcTransport', -) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc_asyncio.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc_asyncio.py deleted file mode 100644 index 8e27253..0000000 --- a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/grpc_asyncio.py +++ /dev/null @@ -1,466 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.analytics.data_v1beta.types import analytics_data_api -from .base import BetaAnalyticsDataTransport, DEFAULT_CLIENT_INFO -from .grpc import BetaAnalyticsDataGrpcTransport - - -class BetaAnalyticsDataGrpcAsyncIOTransport(BetaAnalyticsDataTransport): - """gRPC AsyncIO backend transport for BetaAnalyticsData. - - Google Analytics reporting data service. - - 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 = 'analyticsdata.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'analyticsdata.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def run_report(self) -> Callable[ - [analytics_data_api.RunReportRequest], - Awaitable[analytics_data_api.RunReportResponse]]: - r"""Return a callable for the run report method over gRPC. - - Returns a customized report of your Google Analytics event data. - Reports contain statistics derived from data collected by the - Google Analytics tracking code. The data returned from the API - is as a table with columns for the requested dimensions and - metrics. Metrics are individual measurements of user activity on - your property, such as active users or event count. Dimensions - break down metrics across some common criteria, such as country - or event name. - - For a guide to constructing requests & understanding responses, - see `Creating a - Report `__. - - Returns: - Callable[[~.RunReportRequest], - Awaitable[~.RunReportResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_report' not in self._stubs: - self._stubs['run_report'] = self.grpc_channel.unary_unary( - '/google.analytics.data.v1beta.BetaAnalyticsData/RunReport', - request_serializer=analytics_data_api.RunReportRequest.serialize, - response_deserializer=analytics_data_api.RunReportResponse.deserialize, - ) - return self._stubs['run_report'] - - @property - def run_pivot_report(self) -> Callable[ - [analytics_data_api.RunPivotReportRequest], - Awaitable[analytics_data_api.RunPivotReportResponse]]: - r"""Return a callable for the run pivot report method over gRPC. - - Returns a customized pivot report of your Google - Analytics event data. Pivot reports are more advanced - and expressive formats than regular reports. In a pivot - report, dimensions are only visible if they are included - in a pivot. Multiple pivots can be specified to further - dissect your data. - - Returns: - Callable[[~.RunPivotReportRequest], - Awaitable[~.RunPivotReportResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_pivot_report' not in self._stubs: - self._stubs['run_pivot_report'] = self.grpc_channel.unary_unary( - '/google.analytics.data.v1beta.BetaAnalyticsData/RunPivotReport', - request_serializer=analytics_data_api.RunPivotReportRequest.serialize, - response_deserializer=analytics_data_api.RunPivotReportResponse.deserialize, - ) - return self._stubs['run_pivot_report'] - - @property - def batch_run_reports(self) -> Callable[ - [analytics_data_api.BatchRunReportsRequest], - Awaitable[analytics_data_api.BatchRunReportsResponse]]: - r"""Return a callable for the batch run reports method over gRPC. - - Returns multiple reports in a batch. All reports must - be for the same GA4 Property. - - Returns: - Callable[[~.BatchRunReportsRequest], - Awaitable[~.BatchRunReportsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_run_reports' not in self._stubs: - self._stubs['batch_run_reports'] = self.grpc_channel.unary_unary( - '/google.analytics.data.v1beta.BetaAnalyticsData/BatchRunReports', - request_serializer=analytics_data_api.BatchRunReportsRequest.serialize, - response_deserializer=analytics_data_api.BatchRunReportsResponse.deserialize, - ) - return self._stubs['batch_run_reports'] - - @property - def batch_run_pivot_reports(self) -> Callable[ - [analytics_data_api.BatchRunPivotReportsRequest], - Awaitable[analytics_data_api.BatchRunPivotReportsResponse]]: - r"""Return a callable for the batch run pivot reports method over gRPC. - - Returns multiple pivot reports in a batch. All - reports must be for the same GA4 Property. - - Returns: - Callable[[~.BatchRunPivotReportsRequest], - Awaitable[~.BatchRunPivotReportsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_run_pivot_reports' not in self._stubs: - self._stubs['batch_run_pivot_reports'] = self.grpc_channel.unary_unary( - '/google.analytics.data.v1beta.BetaAnalyticsData/BatchRunPivotReports', - request_serializer=analytics_data_api.BatchRunPivotReportsRequest.serialize, - response_deserializer=analytics_data_api.BatchRunPivotReportsResponse.deserialize, - ) - return self._stubs['batch_run_pivot_reports'] - - @property - def get_metadata(self) -> Callable[ - [analytics_data_api.GetMetadataRequest], - Awaitable[analytics_data_api.Metadata]]: - r"""Return a callable for the get metadata method over gRPC. - - Returns metadata for dimensions and metrics available in - reporting methods. Used to explore the dimensions and metrics. - In this method, a Google Analytics GA4 Property Identifier is - specified in the request, and the metadata response includes - Custom dimensions and metrics as well as Universal metadata. - - For example if a custom metric with parameter name - ``levels_unlocked`` is registered to a property, the Metadata - response will contain ``customEvent:levels_unlocked``. Universal - metadata are dimensions and metrics applicable to any property - such as ``country`` and ``totalUsers``. - - Returns: - Callable[[~.GetMetadataRequest], - Awaitable[~.Metadata]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_metadata' not in self._stubs: - self._stubs['get_metadata'] = self.grpc_channel.unary_unary( - '/google.analytics.data.v1beta.BetaAnalyticsData/GetMetadata', - request_serializer=analytics_data_api.GetMetadataRequest.serialize, - response_deserializer=analytics_data_api.Metadata.deserialize, - ) - return self._stubs['get_metadata'] - - @property - def run_realtime_report(self) -> Callable[ - [analytics_data_api.RunRealtimeReportRequest], - Awaitable[analytics_data_api.RunRealtimeReportResponse]]: - r"""Return a callable for the run realtime report method over gRPC. - - Returns a customized report of realtime event data for your - property. Events appear in realtime reports seconds after they - have been sent to the Google Analytics. Realtime reports show - events and usage data for the periods of time ranging from the - present moment to 30 minutes ago (up to 60 minutes for Google - Analytics 360 properties). - - For a guide to constructing realtime requests & understanding - responses, see `Creating a Realtime - Report `__. - - Returns: - Callable[[~.RunRealtimeReportRequest], - Awaitable[~.RunRealtimeReportResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_realtime_report' not in self._stubs: - self._stubs['run_realtime_report'] = self.grpc_channel.unary_unary( - '/google.analytics.data.v1beta.BetaAnalyticsData/RunRealtimeReport', - request_serializer=analytics_data_api.RunRealtimeReportRequest.serialize, - response_deserializer=analytics_data_api.RunRealtimeReportResponse.deserialize, - ) - return self._stubs['run_realtime_report'] - - @property - def check_compatibility(self) -> Callable[ - [analytics_data_api.CheckCompatibilityRequest], - Awaitable[analytics_data_api.CheckCompatibilityResponse]]: - r"""Return a callable for the check compatibility method over gRPC. - - This compatibility method lists dimensions and - metrics that can be added to a report request and - maintain compatibility. This method fails if the - request's dimensions and metrics are incompatible. - In Google Analytics, reports fail if they request - incompatible dimensions and/or metrics; in that case, - you will need to remove dimensions and/or metrics from - the incompatible report until the report is compatible. - The Realtime and Core reports have different - compatibility rules. This method checks compatibility - for Core reports. - - Returns: - Callable[[~.CheckCompatibilityRequest], - Awaitable[~.CheckCompatibilityResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'check_compatibility' not in self._stubs: - self._stubs['check_compatibility'] = self.grpc_channel.unary_unary( - '/google.analytics.data.v1beta.BetaAnalyticsData/CheckCompatibility', - request_serializer=analytics_data_api.CheckCompatibilityRequest.serialize, - response_deserializer=analytics_data_api.CheckCompatibilityResponse.deserialize, - ) - return self._stubs['check_compatibility'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'BetaAnalyticsDataGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/rest.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/rest.py deleted file mode 100644 index 0be2b18..0000000 --- a/owl-bot-staging/v1beta/google/analytics/data_v1beta/services/beta_analytics_data/transports/rest.py +++ /dev/null @@ -1,970 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.analytics.data_v1beta.types import analytics_data_api - -from .base import BetaAnalyticsDataTransport, 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 BetaAnalyticsDataRestInterceptor: - """Interceptor for BetaAnalyticsData. - - 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 BetaAnalyticsDataRestTransport. - - .. code-block:: python - class MyCustomBetaAnalyticsDataInterceptor(BetaAnalyticsDataRestInterceptor): - def pre_batch_run_pivot_reports(request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_run_pivot_reports(response): - logging.log(f"Received response: {response}") - - def pre_batch_run_reports(request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_run_reports(response): - logging.log(f"Received response: {response}") - - def pre_check_compatibility(request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_check_compatibility(response): - logging.log(f"Received response: {response}") - - def pre_get_metadata(request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_metadata(response): - logging.log(f"Received response: {response}") - - def pre_run_pivot_report(request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_run_pivot_report(response): - logging.log(f"Received response: {response}") - - def pre_run_realtime_report(request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_run_realtime_report(response): - logging.log(f"Received response: {response}") - - def pre_run_report(request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_run_report(response): - logging.log(f"Received response: {response}") - - transport = BetaAnalyticsDataRestTransport(interceptor=MyCustomBetaAnalyticsDataInterceptor()) - client = BetaAnalyticsDataClient(transport=transport) - - - """ - def pre_batch_run_pivot_reports(self, request: analytics_data_api.BatchRunPivotReportsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_data_api.BatchRunPivotReportsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_run_pivot_reports - - Override in a subclass to manipulate the request or metadata - before they are sent to the BetaAnalyticsData server. - """ - return request, metadata - - def post_batch_run_pivot_reports(self, response: analytics_data_api.BatchRunPivotReportsResponse) -> analytics_data_api.BatchRunPivotReportsResponse: - """Post-rpc interceptor for batch_run_pivot_reports - - Override in a subclass to manipulate the response - after it is returned by the BetaAnalyticsData server but before - it is returned to user code. - """ - return response - def pre_batch_run_reports(self, request: analytics_data_api.BatchRunReportsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_data_api.BatchRunReportsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_run_reports - - Override in a subclass to manipulate the request or metadata - before they are sent to the BetaAnalyticsData server. - """ - return request, metadata - - def post_batch_run_reports(self, response: analytics_data_api.BatchRunReportsResponse) -> analytics_data_api.BatchRunReportsResponse: - """Post-rpc interceptor for batch_run_reports - - Override in a subclass to manipulate the response - after it is returned by the BetaAnalyticsData server but before - it is returned to user code. - """ - return response - def pre_check_compatibility(self, request: analytics_data_api.CheckCompatibilityRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_data_api.CheckCompatibilityRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for check_compatibility - - Override in a subclass to manipulate the request or metadata - before they are sent to the BetaAnalyticsData server. - """ - return request, metadata - - def post_check_compatibility(self, response: analytics_data_api.CheckCompatibilityResponse) -> analytics_data_api.CheckCompatibilityResponse: - """Post-rpc interceptor for check_compatibility - - Override in a subclass to manipulate the response - after it is returned by the BetaAnalyticsData server but before - it is returned to user code. - """ - return response - def pre_get_metadata(self, request: analytics_data_api.GetMetadataRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_data_api.GetMetadataRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_metadata - - Override in a subclass to manipulate the request or metadata - before they are sent to the BetaAnalyticsData server. - """ - return request, metadata - - def post_get_metadata(self, response: analytics_data_api.Metadata) -> analytics_data_api.Metadata: - """Post-rpc interceptor for get_metadata - - Override in a subclass to manipulate the response - after it is returned by the BetaAnalyticsData server but before - it is returned to user code. - """ - return response - def pre_run_pivot_report(self, request: analytics_data_api.RunPivotReportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_data_api.RunPivotReportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for run_pivot_report - - Override in a subclass to manipulate the request or metadata - before they are sent to the BetaAnalyticsData server. - """ - return request, metadata - - def post_run_pivot_report(self, response: analytics_data_api.RunPivotReportResponse) -> analytics_data_api.RunPivotReportResponse: - """Post-rpc interceptor for run_pivot_report - - Override in a subclass to manipulate the response - after it is returned by the BetaAnalyticsData server but before - it is returned to user code. - """ - return response - def pre_run_realtime_report(self, request: analytics_data_api.RunRealtimeReportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_data_api.RunRealtimeReportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for run_realtime_report - - Override in a subclass to manipulate the request or metadata - before they are sent to the BetaAnalyticsData server. - """ - return request, metadata - - def post_run_realtime_report(self, response: analytics_data_api.RunRealtimeReportResponse) -> analytics_data_api.RunRealtimeReportResponse: - """Post-rpc interceptor for run_realtime_report - - Override in a subclass to manipulate the response - after it is returned by the BetaAnalyticsData server but before - it is returned to user code. - """ - return response - def pre_run_report(self, request: analytics_data_api.RunReportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_data_api.RunReportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for run_report - - Override in a subclass to manipulate the request or metadata - before they are sent to the BetaAnalyticsData server. - """ - return request, metadata - - def post_run_report(self, response: analytics_data_api.RunReportResponse) -> analytics_data_api.RunReportResponse: - """Post-rpc interceptor for run_report - - Override in a subclass to manipulate the response - after it is returned by the BetaAnalyticsData server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class BetaAnalyticsDataRestStub: - _session: AuthorizedSession - _host: str - _interceptor: BetaAnalyticsDataRestInterceptor - - -class BetaAnalyticsDataRestTransport(BetaAnalyticsDataTransport): - """REST backend transport for BetaAnalyticsData. - - Google Analytics reporting data service. - - 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 - - NOTE: This REST transport functionality is currently in a beta - state (preview). We welcome your feedback via an issue in this - library's source repository. Thank you! - """ - - def __init__(self, *, - host: str = 'analyticsdata.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[BetaAnalyticsDataRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - NOTE: This REST transport functionality is currently in a beta - state (preview). We welcome your feedback via a GitHub issue in - this library's repository. Thank you! - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is 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 BetaAnalyticsDataRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _BatchRunPivotReports(BetaAnalyticsDataRestStub): - def __hash__(self): - return hash("BatchRunPivotReports") - - def __call__(self, - request: analytics_data_api.BatchRunPivotReportsRequest, *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.BatchRunPivotReportsResponse: - r"""Call the batch run pivot reports method over HTTP. - - Args: - request (~.analytics_data_api.BatchRunPivotReportsRequest): - The request object. The batch request containing multiple - pivot report requests. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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_data_api.BatchRunPivotReportsResponse: - The batch response containing - multiple pivot reports. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{property=properties/*}:batchRunPivotReports', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_run_pivot_reports(request, metadata) - pb_request = analytics_data_api.BatchRunPivotReportsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=False - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=False, - )) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._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_data_api.BatchRunPivotReportsResponse() - pb_resp = analytics_data_api.BatchRunPivotReportsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_run_pivot_reports(resp) - return resp - - class _BatchRunReports(BetaAnalyticsDataRestStub): - def __hash__(self): - return hash("BatchRunReports") - - def __call__(self, - request: analytics_data_api.BatchRunReportsRequest, *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.BatchRunReportsResponse: - r"""Call the batch run reports method over HTTP. - - Args: - request (~.analytics_data_api.BatchRunReportsRequest): - The request object. The batch request containing multiple - report requests. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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_data_api.BatchRunReportsResponse: - The batch response containing - multiple reports. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{property=properties/*}:batchRunReports', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_run_reports(request, metadata) - pb_request = analytics_data_api.BatchRunReportsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=False - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=False, - )) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._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_data_api.BatchRunReportsResponse() - pb_resp = analytics_data_api.BatchRunReportsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_run_reports(resp) - return resp - - class _CheckCompatibility(BetaAnalyticsDataRestStub): - def __hash__(self): - return hash("CheckCompatibility") - - def __call__(self, - request: analytics_data_api.CheckCompatibilityRequest, *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.CheckCompatibilityResponse: - r"""Call the check compatibility method over HTTP. - - Args: - request (~.analytics_data_api.CheckCompatibilityRequest): - The request object. The request for compatibility information for a report's - dimensions and metrics. Check compatibility provides a - preview of the compatibility of a report; fields shared - with the ``runReport`` request should be the same values - as in your ``runReport`` request. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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_data_api.CheckCompatibilityResponse: - The compatibility response with the - compatibility of each dimension & - metric. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{property=properties/*}:checkCompatibility', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_check_compatibility(request, metadata) - pb_request = analytics_data_api.CheckCompatibilityRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=False - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=False, - )) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._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_data_api.CheckCompatibilityResponse() - pb_resp = analytics_data_api.CheckCompatibilityResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_check_compatibility(resp) - return resp - - class _GetMetadata(BetaAnalyticsDataRestStub): - def __hash__(self): - return hash("GetMetadata") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_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_data_api.GetMetadataRequest, *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.Metadata: - r"""Call the get metadata method over HTTP. - - Args: - request (~.analytics_data_api.GetMetadataRequest): - The request object. Request for a property's dimension - and metric metadata. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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_data_api.Metadata: - The dimensions and metrics currently - accepted in reporting methods. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=properties/*/metadata}', - }, - ] - request, metadata = self._interceptor.pre_get_metadata(request, metadata) - pb_request = analytics_data_api.GetMetadataRequest.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'], - including_default_value_fields=False, - use_integers_for_enums=False, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, 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_data_api.Metadata() - pb_resp = analytics_data_api.Metadata.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_metadata(resp) - return resp - - class _RunPivotReport(BetaAnalyticsDataRestStub): - def __hash__(self): - return hash("RunPivotReport") - - def __call__(self, - request: analytics_data_api.RunPivotReportRequest, *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.RunPivotReportResponse: - r"""Call the run pivot report method over HTTP. - - Args: - request (~.analytics_data_api.RunPivotReportRequest): - The request object. The request to generate a pivot - 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_data_api.RunPivotReportResponse: - The response pivot report table - corresponding to a pivot request. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{property=properties/*}:runPivotReport', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_run_pivot_report(request, metadata) - pb_request = analytics_data_api.RunPivotReportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=False - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=False, - )) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._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_data_api.RunPivotReportResponse() - pb_resp = analytics_data_api.RunPivotReportResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_run_pivot_report(resp) - return resp - - class _RunRealtimeReport(BetaAnalyticsDataRestStub): - def __hash__(self): - return hash("RunRealtimeReport") - - def __call__(self, - request: analytics_data_api.RunRealtimeReportRequest, *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.RunRealtimeReportResponse: - r"""Call the run realtime report method over HTTP. - - Args: - request (~.analytics_data_api.RunRealtimeReportRequest): - The request object. The request to generate a realtime - 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_data_api.RunRealtimeReportResponse: - The response realtime report table - corresponding to a request. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{property=properties/*}:runRealtimeReport', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_run_realtime_report(request, metadata) - pb_request = analytics_data_api.RunRealtimeReportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=False - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=False, - )) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._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_data_api.RunRealtimeReportResponse() - pb_resp = analytics_data_api.RunRealtimeReportResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_run_realtime_report(resp) - return resp - - class _RunReport(BetaAnalyticsDataRestStub): - def __hash__(self): - return hash("RunReport") - - def __call__(self, - request: analytics_data_api.RunReportRequest, *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_data_api.RunReportResponse: - r"""Call the run report method over HTTP. - - Args: - request (~.analytics_data_api.RunReportRequest): - The request object. The request to generate a 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_data_api.RunReportResponse: - The response report table - corresponding to a request. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{property=properties/*}:runReport', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_run_report(request, metadata) - pb_request = analytics_data_api.RunReportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=False - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=False, - )) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._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_data_api.RunReportResponse() - pb_resp = analytics_data_api.RunReportResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_run_report(resp) - return resp - - @property - def batch_run_pivot_reports(self) -> Callable[ - [analytics_data_api.BatchRunPivotReportsRequest], - analytics_data_api.BatchRunPivotReportsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchRunPivotReports(self._session, self._host, self._interceptor) # type: ignore - - @property - def batch_run_reports(self) -> Callable[ - [analytics_data_api.BatchRunReportsRequest], - analytics_data_api.BatchRunReportsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchRunReports(self._session, self._host, self._interceptor) # type: ignore - - @property - def check_compatibility(self) -> Callable[ - [analytics_data_api.CheckCompatibilityRequest], - analytics_data_api.CheckCompatibilityResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CheckCompatibility(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_metadata(self) -> Callable[ - [analytics_data_api.GetMetadataRequest], - analytics_data_api.Metadata]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetMetadata(self._session, self._host, self._interceptor) # type: ignore - - @property - def run_pivot_report(self) -> Callable[ - [analytics_data_api.RunPivotReportRequest], - analytics_data_api.RunPivotReportResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._RunPivotReport(self._session, self._host, self._interceptor) # type: ignore - - @property - def run_realtime_report(self) -> Callable[ - [analytics_data_api.RunRealtimeReportRequest], - analytics_data_api.RunRealtimeReportResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._RunRealtimeReport(self._session, self._host, self._interceptor) # type: ignore - - @property - def run_report(self) -> Callable[ - [analytics_data_api.RunReportRequest], - analytics_data_api.RunReportResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._RunReport(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'BetaAnalyticsDataRestTransport', -) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/types/__init__.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/types/__init__.py deleted file mode 100644 index 36ff6ec..0000000 --- a/owl-bot-staging/v1beta/google/analytics/data_v1beta/types/__init__.py +++ /dev/null @@ -1,116 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .analytics_data_api import ( - BatchRunPivotReportsRequest, - BatchRunPivotReportsResponse, - BatchRunReportsRequest, - BatchRunReportsResponse, - CheckCompatibilityRequest, - CheckCompatibilityResponse, - GetMetadataRequest, - Metadata, - RunPivotReportRequest, - RunPivotReportResponse, - RunRealtimeReportRequest, - RunRealtimeReportResponse, - RunReportRequest, - RunReportResponse, -) -from .data import ( - Cohort, - CohortReportSettings, - CohortSpec, - CohortsRange, - DateRange, - Dimension, - DimensionCompatibility, - DimensionExpression, - DimensionHeader, - DimensionMetadata, - DimensionValue, - Filter, - FilterExpression, - FilterExpressionList, - Metric, - MetricCompatibility, - MetricHeader, - MetricMetadata, - MetricValue, - MinuteRange, - NumericValue, - OrderBy, - Pivot, - PivotDimensionHeader, - PivotHeader, - PropertyQuota, - QuotaStatus, - ResponseMetaData, - Row, - Compatibility, - MetricAggregation, - MetricType, - RestrictedMetricType, -) - -__all__ = ( - 'BatchRunPivotReportsRequest', - 'BatchRunPivotReportsResponse', - 'BatchRunReportsRequest', - 'BatchRunReportsResponse', - 'CheckCompatibilityRequest', - 'CheckCompatibilityResponse', - 'GetMetadataRequest', - 'Metadata', - 'RunPivotReportRequest', - 'RunPivotReportResponse', - 'RunRealtimeReportRequest', - 'RunRealtimeReportResponse', - 'RunReportRequest', - 'RunReportResponse', - 'Cohort', - 'CohortReportSettings', - 'CohortSpec', - 'CohortsRange', - 'DateRange', - 'Dimension', - 'DimensionCompatibility', - 'DimensionExpression', - 'DimensionHeader', - 'DimensionMetadata', - 'DimensionValue', - 'Filter', - 'FilterExpression', - 'FilterExpressionList', - 'Metric', - 'MetricCompatibility', - 'MetricHeader', - 'MetricMetadata', - 'MetricValue', - 'MinuteRange', - 'NumericValue', - 'OrderBy', - 'Pivot', - 'PivotDimensionHeader', - 'PivotHeader', - 'PropertyQuota', - 'QuotaStatus', - 'ResponseMetaData', - 'Row', - 'Compatibility', - 'MetricAggregation', - 'MetricType', - 'RestrictedMetricType', -) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/types/analytics_data_api.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/types/analytics_data_api.py deleted file mode 100644 index 41abbfc..0000000 --- a/owl-bot-staging/v1beta/google/analytics/data_v1beta/types/analytics_data_api.py +++ /dev/null @@ -1,978 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.analytics.data_v1beta.types import data - - -__protobuf__ = proto.module( - package='google.analytics.data.v1beta', - manifest={ - 'CheckCompatibilityRequest', - 'CheckCompatibilityResponse', - 'Metadata', - 'RunReportRequest', - 'RunReportResponse', - 'RunPivotReportRequest', - 'RunPivotReportResponse', - 'BatchRunReportsRequest', - 'BatchRunReportsResponse', - 'BatchRunPivotReportsRequest', - 'BatchRunPivotReportsResponse', - 'GetMetadataRequest', - 'RunRealtimeReportRequest', - 'RunRealtimeReportResponse', - }, -) - - -class CheckCompatibilityRequest(proto.Message): - r"""The request for compatibility information for a report's dimensions - and metrics. Check compatibility provides a preview of the - compatibility of a report; fields shared with the ``runReport`` - request should be the same values as in your ``runReport`` request. - - Attributes: - property (str): - A Google Analytics GA4 property identifier whose events are - tracked. To learn more, see `where to find your Property - ID `__. - ``property`` should be the same value as in your - ``runReport`` request. - - Example: properties/1234 - - Set the Property ID to 0 for compatibility checking on - dimensions and metrics common to all properties. In this - special mode, this method will not return custom dimensions - and metrics. - dimensions (MutableSequence[google.analytics.data_v1beta.types.Dimension]): - The dimensions in this report. ``dimensions`` should be the - same value as in your ``runReport`` request. - metrics (MutableSequence[google.analytics.data_v1beta.types.Metric]): - The metrics in this report. ``metrics`` should be the same - value as in your ``runReport`` request. - dimension_filter (google.analytics.data_v1beta.types.FilterExpression): - The filter clause of dimensions. ``dimensionFilter`` should - be the same value as in your ``runReport`` request. - metric_filter (google.analytics.data_v1beta.types.FilterExpression): - The filter clause of metrics. ``metricFilter`` should be the - same value as in your ``runReport`` request - compatibility_filter (google.analytics.data_v1beta.types.Compatibility): - Filters the dimensions and metrics in the response to just - this compatibility. Commonly used as - ``”compatibilityFilter”: “COMPATIBLE”`` to only return - compatible dimensions & metrics. - """ - - property: str = proto.Field( - proto.STRING, - number=1, - ) - dimensions: MutableSequence[data.Dimension] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=data.Dimension, - ) - metrics: MutableSequence[data.Metric] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=data.Metric, - ) - dimension_filter: data.FilterExpression = proto.Field( - proto.MESSAGE, - number=4, - message=data.FilterExpression, - ) - metric_filter: data.FilterExpression = proto.Field( - proto.MESSAGE, - number=5, - message=data.FilterExpression, - ) - compatibility_filter: data.Compatibility = proto.Field( - proto.ENUM, - number=6, - enum=data.Compatibility, - ) - - -class CheckCompatibilityResponse(proto.Message): - r"""The compatibility response with the compatibility of each - dimension & metric. - - Attributes: - dimension_compatibilities (MutableSequence[google.analytics.data_v1beta.types.DimensionCompatibility]): - The compatibility of each dimension. - metric_compatibilities (MutableSequence[google.analytics.data_v1beta.types.MetricCompatibility]): - The compatibility of each metric. - """ - - dimension_compatibilities: MutableSequence[data.DimensionCompatibility] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=data.DimensionCompatibility, - ) - metric_compatibilities: MutableSequence[data.MetricCompatibility] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=data.MetricCompatibility, - ) - - -class Metadata(proto.Message): - r"""The dimensions and metrics currently accepted in reporting - methods. - - Attributes: - name (str): - Resource name of this metadata. - dimensions (MutableSequence[google.analytics.data_v1beta.types.DimensionMetadata]): - The dimension descriptions. - metrics (MutableSequence[google.analytics.data_v1beta.types.MetricMetadata]): - The metric descriptions. - """ - - name: str = proto.Field( - proto.STRING, - number=3, - ) - dimensions: MutableSequence[data.DimensionMetadata] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=data.DimensionMetadata, - ) - metrics: MutableSequence[data.MetricMetadata] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=data.MetricMetadata, - ) - - -class RunReportRequest(proto.Message): - r"""The request to generate a report. - - Attributes: - property (str): - A Google Analytics GA4 property identifier whose events are - tracked. Specified in the URL path and not the body. To - learn more, see `where to find your Property - ID `__. - Within a batch request, this property should either be - unspecified or consistent with the batch-level property. - - Example: properties/1234 - dimensions (MutableSequence[google.analytics.data_v1beta.types.Dimension]): - The dimensions requested and displayed. - metrics (MutableSequence[google.analytics.data_v1beta.types.Metric]): - The metrics requested and displayed. - date_ranges (MutableSequence[google.analytics.data_v1beta.types.DateRange]): - Date ranges of data 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 event data for - the overlapping days is included in the response rows for - both date ranges. In a cohort request, this ``dateRanges`` - must be unspecified. - dimension_filter (google.analytics.data_v1beta.types.FilterExpression): - Dimension filters allow you to ask for only specific - dimension values in the report. To learn more, see - `Fundamentals of Dimension - Filters `__ - for examples. Metrics cannot be used in this filter. - metric_filter (google.analytics.data_v1beta.types.FilterExpression): - The filter clause of metrics. 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. - - When paging, the first request does not specify offset; or - equivalently, sets offset to 0; the first request returns - the first ``limit`` of rows. The second request sets offset - to the ``limit`` of the first request; the second request - returns the second ``limit`` of rows. - - 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 can also return fewer rows than the requested - ``limit``, if there aren't as many dimension values 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 `__. - metric_aggregations (MutableSequence[google.analytics.data_v1beta.types.MetricAggregation]): - Aggregation of metrics. Aggregated metric values will be - shown in rows where the dimension_values are set to - "RESERVED_(MetricAggregation)". - order_bys (MutableSequence[google.analytics.data_v1beta.types.OrderBy]): - Specifies how rows are ordered in the - response. - currency_code (str): - A currency code in ISO4217 format, such as - "AED", "USD", "JPY". If the field is empty, the - report uses the property's default currency. - cohort_spec (google.analytics.data_v1beta.types.CohortSpec): - Cohort group associated with this request. If - there is a cohort group in the request the - 'cohort' dimension must be present. - keep_empty_rows (bool): - If false or unspecified, each row with all - metrics equal to 0 will not be returned. If - true, these rows will be returned if they are - not separately removed by a filter. - return_property_quota (bool): - Toggles whether to return the current state of this - Analytics Property's quota. Quota is returned in - `PropertyQuota <#PropertyQuota>`__. - """ - - property: str = proto.Field( - proto.STRING, - number=1, - ) - dimensions: MutableSequence[data.Dimension] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=data.Dimension, - ) - metrics: MutableSequence[data.Metric] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=data.Metric, - ) - date_ranges: MutableSequence[data.DateRange] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=data.DateRange, - ) - dimension_filter: data.FilterExpression = proto.Field( - proto.MESSAGE, - number=5, - message=data.FilterExpression, - ) - metric_filter: data.FilterExpression = proto.Field( - proto.MESSAGE, - number=6, - message=data.FilterExpression, - ) - offset: int = proto.Field( - proto.INT64, - number=7, - ) - limit: int = proto.Field( - proto.INT64, - number=8, - ) - metric_aggregations: MutableSequence[data.MetricAggregation] = proto.RepeatedField( - proto.ENUM, - number=9, - enum=data.MetricAggregation, - ) - order_bys: MutableSequence[data.OrderBy] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=data.OrderBy, - ) - currency_code: str = proto.Field( - proto.STRING, - number=11, - ) - cohort_spec: data.CohortSpec = proto.Field( - proto.MESSAGE, - number=12, - message=data.CohortSpec, - ) - keep_empty_rows: bool = proto.Field( - proto.BOOL, - number=13, - ) - return_property_quota: bool = proto.Field( - proto.BOOL, - number=14, - ) - - -class RunReportResponse(proto.Message): - r"""The response report table corresponding to a request. - - Attributes: - dimension_headers (MutableSequence[google.analytics.data_v1beta.types.DimensionHeader]): - Describes dimension columns. The number of - DimensionHeaders and ordering of - DimensionHeaders matches the dimensions present - in rows. - metric_headers (MutableSequence[google.analytics.data_v1beta.types.MetricHeader]): - Describes metric columns. The number of - MetricHeaders and ordering of MetricHeaders - matches the metrics present in rows. - rows (MutableSequence[google.analytics.data_v1beta.types.Row]): - Rows of dimension value combinations and - metric values in the report. - totals (MutableSequence[google.analytics.data_v1beta.types.Row]): - If requested, the totaled values of metrics. - maximums (MutableSequence[google.analytics.data_v1beta.types.Row]): - If requested, the maximum values of metrics. - minimums (MutableSequence[google.analytics.data_v1beta.types.Row]): - If requested, the minimum values of metrics. - 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 `__. - metadata (google.analytics.data_v1beta.types.ResponseMetaData): - Metadata for the report. - property_quota (google.analytics.data_v1beta.types.PropertyQuota): - This Analytics Property's quota state - including this request. - kind (str): - Identifies what kind of resource this message is. This - ``kind`` is always the fixed string - "analyticsData#runReport". Useful to distinguish between - response types in JSON. - """ - - dimension_headers: MutableSequence[data.DimensionHeader] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=data.DimensionHeader, - ) - metric_headers: MutableSequence[data.MetricHeader] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=data.MetricHeader, - ) - rows: MutableSequence[data.Row] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=data.Row, - ) - totals: MutableSequence[data.Row] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=data.Row, - ) - maximums: MutableSequence[data.Row] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=data.Row, - ) - minimums: MutableSequence[data.Row] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=data.Row, - ) - row_count: int = proto.Field( - proto.INT32, - number=7, - ) - metadata: data.ResponseMetaData = proto.Field( - proto.MESSAGE, - number=8, - message=data.ResponseMetaData, - ) - property_quota: data.PropertyQuota = proto.Field( - proto.MESSAGE, - number=9, - message=data.PropertyQuota, - ) - kind: str = proto.Field( - proto.STRING, - number=10, - ) - - -class RunPivotReportRequest(proto.Message): - r"""The request to generate a pivot report. - - Attributes: - property (str): - A Google Analytics GA4 property identifier whose events are - tracked. Specified in the URL path and not the body. To - learn more, see `where to find your Property - ID `__. - Within a batch request, this property should either be - unspecified or consistent with the batch-level property. - - Example: properties/1234 - dimensions (MutableSequence[google.analytics.data_v1beta.types.Dimension]): - The dimensions requested. All defined dimensions must be - used by one of the following: dimension_expression, - dimension_filter, pivots, order_bys. - metrics (MutableSequence[google.analytics.data_v1beta.types.Metric]): - The metrics requested, at least one metric needs to be - specified. All defined metrics must be used by one of the - following: metric_expression, metric_filter, order_bys. - date_ranges (MutableSequence[google.analytics.data_v1beta.types.DateRange]): - The date range to retrieve event data for the report. If - multiple date ranges are specified, event data from each - date range is used in the report. A special dimension with - field name "dateRange" can be included in a Pivot's field - names; if included, the report compares between date ranges. - In a cohort request, this ``dateRanges`` must be - unspecified. - pivots (MutableSequence[google.analytics.data_v1beta.types.Pivot]): - Describes the visual format of the report's - dimensions in columns or rows. The union of the - fieldNames (dimension names) in all pivots must - be a subset of dimension names defined in - Dimensions. No two pivots can share a dimension. - A dimension is only visible if it appears in a - pivot. - dimension_filter (google.analytics.data_v1beta.types.FilterExpression): - The filter clause of dimensions. Dimensions - must be requested to be used in this filter. - Metrics cannot be used in this filter. - metric_filter (google.analytics.data_v1beta.types.FilterExpression): - The filter clause of metrics. Applied at post - aggregation phase, similar to SQL having-clause. - Metrics must be requested to be used in this - filter. Dimensions cannot be used in this - filter. - currency_code (str): - A currency code in ISO4217 format, such as - "AED", "USD", "JPY". If the field is empty, the - report uses the property's default currency. - cohort_spec (google.analytics.data_v1beta.types.CohortSpec): - Cohort group associated with this request. If - there is a cohort group in the request the - 'cohort' dimension must be present. - keep_empty_rows (bool): - If false or unspecified, each row with all - metrics equal to 0 will not be returned. If - true, these rows will be returned if they are - not separately removed by a filter. - return_property_quota (bool): - Toggles whether to return the current state of this - Analytics Property's quota. Quota is returned in - `PropertyQuota <#PropertyQuota>`__. - """ - - property: str = proto.Field( - proto.STRING, - number=1, - ) - dimensions: MutableSequence[data.Dimension] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=data.Dimension, - ) - metrics: MutableSequence[data.Metric] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=data.Metric, - ) - date_ranges: MutableSequence[data.DateRange] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=data.DateRange, - ) - pivots: MutableSequence[data.Pivot] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=data.Pivot, - ) - dimension_filter: data.FilterExpression = proto.Field( - proto.MESSAGE, - number=6, - message=data.FilterExpression, - ) - metric_filter: data.FilterExpression = proto.Field( - proto.MESSAGE, - number=7, - message=data.FilterExpression, - ) - currency_code: str = proto.Field( - proto.STRING, - number=8, - ) - cohort_spec: data.CohortSpec = proto.Field( - proto.MESSAGE, - number=9, - message=data.CohortSpec, - ) - keep_empty_rows: bool = proto.Field( - proto.BOOL, - number=10, - ) - return_property_quota: bool = proto.Field( - proto.BOOL, - number=11, - ) - - -class RunPivotReportResponse(proto.Message): - r"""The response pivot report table corresponding to a pivot - request. - - Attributes: - pivot_headers (MutableSequence[google.analytics.data_v1beta.types.PivotHeader]): - Summarizes the columns and rows created by a pivot. Each - pivot in the request produces one header in the response. If - we have a request like this: - - :: - - "pivots": [{ - "fieldNames": ["country", - "city"] - }, - { - "fieldNames": "eventName" - }] - - We will have the following ``pivotHeaders`` in the response: - - :: - - "pivotHeaders" : [{ - "dimensionHeaders": [{ - "dimensionValues": [ - { "value": "United Kingdom" }, - { "value": "London" } - ] - }, - { - "dimensionValues": [ - { "value": "Japan" }, - { "value": "Osaka" } - ] - }] - }, - { - "dimensionHeaders": [{ - "dimensionValues": [{ "value": "session_start" }] - }, - { - "dimensionValues": [{ "value": "scroll" }] - }] - }] - dimension_headers (MutableSequence[google.analytics.data_v1beta.types.DimensionHeader]): - Describes dimension columns. The number of - DimensionHeaders and ordering of - DimensionHeaders matches the dimensions present - in rows. - metric_headers (MutableSequence[google.analytics.data_v1beta.types.MetricHeader]): - Describes metric columns. The number of - MetricHeaders and ordering of MetricHeaders - matches the metrics present in rows. - rows (MutableSequence[google.analytics.data_v1beta.types.Row]): - Rows of dimension value combinations and - metric values in the report. - aggregates (MutableSequence[google.analytics.data_v1beta.types.Row]): - Aggregation of metric values. Can be totals, minimums, or - maximums. The returned aggregations are controlled by the - metric_aggregations in the pivot. The type of aggregation - returned in each row is shown by the dimension_values which - are set to "RESERVED\_". - metadata (google.analytics.data_v1beta.types.ResponseMetaData): - Metadata for the report. - property_quota (google.analytics.data_v1beta.types.PropertyQuota): - This Analytics Property's quota state - including this request. - kind (str): - Identifies what kind of resource this message is. This - ``kind`` is always the fixed string - "analyticsData#runPivotReport". Useful to distinguish - between response types in JSON. - """ - - pivot_headers: MutableSequence[data.PivotHeader] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=data.PivotHeader, - ) - dimension_headers: MutableSequence[data.DimensionHeader] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=data.DimensionHeader, - ) - metric_headers: MutableSequence[data.MetricHeader] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=data.MetricHeader, - ) - rows: MutableSequence[data.Row] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=data.Row, - ) - aggregates: MutableSequence[data.Row] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=data.Row, - ) - metadata: data.ResponseMetaData = proto.Field( - proto.MESSAGE, - number=6, - message=data.ResponseMetaData, - ) - property_quota: data.PropertyQuota = proto.Field( - proto.MESSAGE, - number=7, - message=data.PropertyQuota, - ) - kind: str = proto.Field( - proto.STRING, - number=8, - ) - - -class BatchRunReportsRequest(proto.Message): - r"""The batch request containing multiple report requests. - - Attributes: - property (str): - A Google Analytics GA4 property identifier whose events are - tracked. Specified in the URL path and not the body. To - learn more, see `where to find your Property - ID `__. - This property must be specified for the batch. The property - within RunReportRequest may either be unspecified or - consistent with this property. - - Example: properties/1234 - requests (MutableSequence[google.analytics.data_v1beta.types.RunReportRequest]): - Individual requests. Each request has a - separate report response. Each batch request is - allowed up to 5 requests. - """ - - property: str = proto.Field( - proto.STRING, - number=1, - ) - requests: MutableSequence['RunReportRequest'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='RunReportRequest', - ) - - -class BatchRunReportsResponse(proto.Message): - r"""The batch response containing multiple reports. - - Attributes: - reports (MutableSequence[google.analytics.data_v1beta.types.RunReportResponse]): - Individual responses. Each response has a - separate report request. - kind (str): - Identifies what kind of resource this message is. This - ``kind`` is always the fixed string - "analyticsData#batchRunReports". Useful to distinguish - between response types in JSON. - """ - - reports: MutableSequence['RunReportResponse'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RunReportResponse', - ) - kind: str = proto.Field( - proto.STRING, - number=2, - ) - - -class BatchRunPivotReportsRequest(proto.Message): - r"""The batch request containing multiple pivot report requests. - - Attributes: - property (str): - A Google Analytics GA4 property identifier whose events are - tracked. Specified in the URL path and not the body. To - learn more, see `where to find your Property - ID `__. - This property must be specified for the batch. The property - within RunPivotReportRequest may either be unspecified or - consistent with this property. - - Example: properties/1234 - requests (MutableSequence[google.analytics.data_v1beta.types.RunPivotReportRequest]): - Individual requests. Each request has a - separate pivot report response. Each batch - request is allowed up to 5 requests. - """ - - property: str = proto.Field( - proto.STRING, - number=1, - ) - requests: MutableSequence['RunPivotReportRequest'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='RunPivotReportRequest', - ) - - -class BatchRunPivotReportsResponse(proto.Message): - r"""The batch response containing multiple pivot reports. - - Attributes: - pivot_reports (MutableSequence[google.analytics.data_v1beta.types.RunPivotReportResponse]): - Individual responses. Each response has a - separate pivot report request. - kind (str): - Identifies what kind of resource this message is. This - ``kind`` is always the fixed string - "analyticsData#batchRunPivotReports". Useful to distinguish - between response types in JSON. - """ - - pivot_reports: MutableSequence['RunPivotReportResponse'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RunPivotReportResponse', - ) - kind: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetMetadataRequest(proto.Message): - r"""Request for a property's dimension and metric metadata. - - Attributes: - name (str): - Required. The resource name of the metadata to retrieve. - This name field is specified in the URL path and not URL - parameters. Property is a numeric Google Analytics GA4 - Property identifier. To learn more, see `where to find your - Property - ID `__. - - Example: properties/1234/metadata - - Set the Property ID to 0 for dimensions and metrics common - to all properties. In this special mode, this method will - not return custom dimensions and metrics. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class RunRealtimeReportRequest(proto.Message): - r"""The request to generate a realtime report. - - Attributes: - property (str): - A Google Analytics GA4 property identifier whose events are - tracked. Specified in the URL path and not the body. To - learn more, see `where to find your Property - ID `__. - - Example: properties/1234 - dimensions (MutableSequence[google.analytics.data_v1beta.types.Dimension]): - The dimensions requested and displayed. - metrics (MutableSequence[google.analytics.data_v1beta.types.Metric]): - The metrics requested and displayed. - dimension_filter (google.analytics.data_v1beta.types.FilterExpression): - The filter clause of dimensions. Metrics - cannot be used in this filter. - metric_filter (google.analytics.data_v1beta.types.FilterExpression): - The filter clause of metrics. Applied at post - aggregation phase, similar to SQL having-clause. - Dimensions cannot be used in this filter. - 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 can also return fewer rows than the requested - ``limit``, if there aren't as many dimension values 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. - metric_aggregations (MutableSequence[google.analytics.data_v1beta.types.MetricAggregation]): - Aggregation of metrics. Aggregated metric values will be - shown in rows where the dimension_values are set to - "RESERVED_(MetricAggregation)". - order_bys (MutableSequence[google.analytics.data_v1beta.types.OrderBy]): - Specifies how rows are ordered in the - response. - return_property_quota (bool): - Toggles whether to return the current state of this - Analytics Property's Realtime quota. Quota is returned in - `PropertyQuota <#PropertyQuota>`__. - minute_ranges (MutableSequence[google.analytics.data_v1beta.types.MinuteRange]): - The minute ranges of event data to read. If - unspecified, one minute range for the last 30 - minutes will be used. If multiple minute ranges - are requested, each response row will contain a - zero based minute range index. If two minute - ranges overlap, the event data for the - overlapping minutes is included in the response - rows for both minute ranges. - """ - - property: str = proto.Field( - proto.STRING, - number=1, - ) - dimensions: MutableSequence[data.Dimension] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=data.Dimension, - ) - metrics: MutableSequence[data.Metric] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=data.Metric, - ) - dimension_filter: data.FilterExpression = proto.Field( - proto.MESSAGE, - number=4, - message=data.FilterExpression, - ) - metric_filter: data.FilterExpression = proto.Field( - proto.MESSAGE, - number=5, - message=data.FilterExpression, - ) - limit: int = proto.Field( - proto.INT64, - number=6, - ) - metric_aggregations: MutableSequence[data.MetricAggregation] = proto.RepeatedField( - proto.ENUM, - number=7, - enum=data.MetricAggregation, - ) - order_bys: MutableSequence[data.OrderBy] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=data.OrderBy, - ) - return_property_quota: bool = proto.Field( - proto.BOOL, - number=9, - ) - minute_ranges: MutableSequence[data.MinuteRange] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=data.MinuteRange, - ) - - -class RunRealtimeReportResponse(proto.Message): - r"""The response realtime report table corresponding to a - request. - - Attributes: - dimension_headers (MutableSequence[google.analytics.data_v1beta.types.DimensionHeader]): - Describes dimension columns. The number of - DimensionHeaders and ordering of - DimensionHeaders matches the dimensions present - in rows. - metric_headers (MutableSequence[google.analytics.data_v1beta.types.MetricHeader]): - Describes metric columns. The number of - MetricHeaders and ordering of MetricHeaders - matches the metrics present in rows. - rows (MutableSequence[google.analytics.data_v1beta.types.Row]): - Rows of dimension value combinations and - metric values in the report. - totals (MutableSequence[google.analytics.data_v1beta.types.Row]): - If requested, the totaled values of metrics. - maximums (MutableSequence[google.analytics.data_v1beta.types.Row]): - If requested, the maximum values of metrics. - minimums (MutableSequence[google.analytics.data_v1beta.types.Row]): - If requested, the minimum values of metrics. - row_count (int): - The total number of rows in the query result. ``rowCount`` - is independent of the number of rows returned in the - response and the ``limit`` 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. - property_quota (google.analytics.data_v1beta.types.PropertyQuota): - This Analytics Property's Realtime quota - state including this request. - kind (str): - Identifies what kind of resource this message is. This - ``kind`` is always the fixed string - "analyticsData#runRealtimeReport". Useful to distinguish - between response types in JSON. - """ - - dimension_headers: MutableSequence[data.DimensionHeader] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=data.DimensionHeader, - ) - metric_headers: MutableSequence[data.MetricHeader] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=data.MetricHeader, - ) - rows: MutableSequence[data.Row] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=data.Row, - ) - totals: MutableSequence[data.Row] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=data.Row, - ) - maximums: MutableSequence[data.Row] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=data.Row, - ) - minimums: MutableSequence[data.Row] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=data.Row, - ) - row_count: int = proto.Field( - proto.INT32, - number=7, - ) - property_quota: data.PropertyQuota = proto.Field( - proto.MESSAGE, - number=8, - message=data.PropertyQuota, - ) - kind: str = proto.Field( - proto.STRING, - number=9, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/analytics/data_v1beta/types/data.py b/owl-bot-staging/v1beta/google/analytics/data_v1beta/types/data.py deleted file mode 100644 index 9c0e869..0000000 --- a/owl-bot-staging/v1beta/google/analytics/data_v1beta/types/data.py +++ /dev/null @@ -1,1693 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.analytics.data.v1beta', - manifest={ - 'MetricAggregation', - 'MetricType', - 'RestrictedMetricType', - 'Compatibility', - 'DateRange', - 'MinuteRange', - 'Dimension', - 'DimensionExpression', - 'Metric', - 'FilterExpression', - 'FilterExpressionList', - 'Filter', - 'OrderBy', - 'Pivot', - 'CohortSpec', - 'Cohort', - 'CohortsRange', - 'CohortReportSettings', - 'ResponseMetaData', - 'DimensionHeader', - 'MetricHeader', - 'PivotHeader', - 'PivotDimensionHeader', - 'Row', - 'DimensionValue', - 'MetricValue', - 'NumericValue', - 'PropertyQuota', - 'QuotaStatus', - 'DimensionMetadata', - 'MetricMetadata', - 'DimensionCompatibility', - 'MetricCompatibility', - }, -) - - -class MetricAggregation(proto.Enum): - r"""Represents aggregation of metrics.""" - METRIC_AGGREGATION_UNSPECIFIED = 0 - TOTAL = 1 - MINIMUM = 5 - MAXIMUM = 6 - COUNT = 4 - - -class MetricType(proto.Enum): - r"""A metric's value type.""" - METRIC_TYPE_UNSPECIFIED = 0 - TYPE_INTEGER = 1 - TYPE_FLOAT = 2 - TYPE_SECONDS = 4 - TYPE_MILLISECONDS = 5 - TYPE_MINUTES = 6 - TYPE_HOURS = 7 - TYPE_STANDARD = 8 - TYPE_CURRENCY = 9 - TYPE_FEET = 10 - TYPE_MILES = 11 - TYPE_METERS = 12 - TYPE_KILOMETERS = 13 - - -class RestrictedMetricType(proto.Enum): - r"""Categories of data that you may be restricted from viewing on - certain GA4 properties. - """ - RESTRICTED_METRIC_TYPE_UNSPECIFIED = 0 - COST_DATA = 1 - REVENUE_DATA = 2 - - -class Compatibility(proto.Enum): - r"""The compatibility types for a single dimension or metric.""" - COMPATIBILITY_UNSPECIFIED = 0 - COMPATIBLE = 1 - INCOMPATIBLE = 2 - - -class DateRange(proto.Message): - r"""A contiguous set of days: startDate, startDate + 1, ..., - endDate. Requests are allowed up to 4 date ranges. - - Attributes: - start_date (str): - The inclusive start date for the query in the format - ``YYYY-MM-DD``. Cannot be after ``end_date``. The format - ``NdaysAgo``, ``yesterday``, or ``today`` is also accepted, - and in that case, the date is inferred based on the - property's reporting time zone. - end_date (str): - The inclusive end date for the query in the format - ``YYYY-MM-DD``. Cannot be before ``start_date``. The format - ``NdaysAgo``, ``yesterday``, or ``today`` is also accepted, - and in that case, the date is inferred based on the - property's reporting time zone. - name (str): - Assigns a name to this date range. The dimension - ``dateRange`` is valued to this name in a report response. - If set, cannot begin with ``date_range_`` or ``RESERVED_``. - If not set, date ranges are named by their zero based index - in the request: ``date_range_0``, ``date_range_1``, etc. - """ - - start_date: str = proto.Field( - proto.STRING, - number=1, - ) - end_date: str = proto.Field( - proto.STRING, - number=2, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - -class MinuteRange(proto.Message): - r"""A contiguous set of minutes: startMinutesAgo, startMinutesAgo - + 1, ..., endMinutesAgo. Requests are allowed up to 2 minute - ranges. - - Attributes: - start_minutes_ago (int): - The inclusive start minute for the query as a number of - minutes before now. For example, ``"startMinutesAgo": 29`` - specifies the report should include event data from 29 - minutes ago and after. Cannot be after ``endMinutesAgo``. - - If unspecified, ``startMinutesAgo`` is defaulted to 29. - Standard Analytics properties can request up to the last 30 - minutes of event data (``startMinutesAgo <= 29``), and 360 - Analytics properties can request up to the last 60 minutes - of event data (``startMinutesAgo <= 59``). - - This field is a member of `oneof`_ ``_start_minutes_ago``. - end_minutes_ago (int): - The inclusive end minute for the query as a number of - minutes before now. Cannot be before ``startMinutesAgo``. - For example, ``"endMinutesAgo": 15`` specifies the report - should include event data from prior to 15 minutes ago. - - If unspecified, ``endMinutesAgo`` is defaulted to 0. - Standard Analytics properties can request any minute in the - last 30 minutes of event data (``endMinutesAgo <= 29``), and - 360 Analytics properties can request any minute in the last - 60 minutes of event data (``endMinutesAgo <= 59``). - - This field is a member of `oneof`_ ``_end_minutes_ago``. - name (str): - Assigns a name to this minute range. The dimension - ``dateRange`` is valued to this name in a report response. - If set, cannot begin with ``date_range_`` or ``RESERVED_``. - If not set, minute ranges are named by their zero based - index in the request: ``date_range_0``, ``date_range_1``, - etc. - """ - - start_minutes_ago: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - end_minutes_ago: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - -class Dimension(proto.Message): - r"""Dimensions are attributes of your data. For example, the - dimension city indicates the city from which an event - originates. Dimension values in report responses are strings; - for example, the city could be "Paris" or "New York". Requests - are allowed up to 9 dimensions. - - Attributes: - name (str): - The name of the dimension. See the `API - Dimensions `__ - for the list of dimension names. - - If ``dimensionExpression`` is specified, ``name`` can be any - string that you would like within the allowed character set. - For example if a ``dimensionExpression`` concatenates - ``country`` and ``city``, you could call that dimension - ``countryAndCity``. Dimension names that you choose must - match the regular expression ``^[a-zA-Z0-9_]$``. - - Dimensions are referenced by ``name`` in - ``dimensionFilter``, ``orderBys``, ``dimensionExpression``, - and ``pivots``. - dimension_expression (google.analytics.data_v1beta.types.DimensionExpression): - One dimension can be the result of an - expression of multiple dimensions. For example, - dimension "country, city": concatenate(country, - ", ", city). - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - dimension_expression: 'DimensionExpression' = proto.Field( - proto.MESSAGE, - number=2, - message='DimensionExpression', - ) - - -class DimensionExpression(proto.Message): - r"""Used to express a dimension which is the result of a formula of - multiple dimensions. Example usages: - - 1) lower_case(dimension) - 2) concatenate(dimension1, symbol, dimension2). - - 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: - lower_case (google.analytics.data_v1beta.types.DimensionExpression.CaseExpression): - Used to convert a dimension value to lower - case. - - This field is a member of `oneof`_ ``one_expression``. - upper_case (google.analytics.data_v1beta.types.DimensionExpression.CaseExpression): - Used to convert a dimension value to upper - case. - - This field is a member of `oneof`_ ``one_expression``. - concatenate (google.analytics.data_v1beta.types.DimensionExpression.ConcatenateExpression): - Used to combine dimension values to a single - dimension. For example, dimension "country, - city": concatenate(country, ", ", city). - - This field is a member of `oneof`_ ``one_expression``. - """ - - class CaseExpression(proto.Message): - r"""Used to convert a dimension value to a single case. - - Attributes: - dimension_name (str): - Name of a dimension. The name must refer back - to a name in dimensions field of the request. - """ - - dimension_name: str = proto.Field( - proto.STRING, - number=1, - ) - - class ConcatenateExpression(proto.Message): - r"""Used to combine dimension values to a single dimension. - - Attributes: - dimension_names (MutableSequence[str]): - Names of dimensions. The names must refer - back to names in the dimensions field of the - request. - delimiter (str): - The delimiter placed between dimension names. - - Delimiters are often single characters such as "|" or "," - but can be longer strings. If a dimension value contains the - delimiter, both will be present in response with no - distinction. For example if dimension 1 value = "US,FR", - dimension 2 value = "JP", and delimiter = ",", then the - response will contain "US,FR,JP". - """ - - dimension_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - delimiter: str = proto.Field( - proto.STRING, - number=2, - ) - - lower_case: CaseExpression = proto.Field( - proto.MESSAGE, - number=4, - oneof='one_expression', - message=CaseExpression, - ) - upper_case: CaseExpression = proto.Field( - proto.MESSAGE, - number=5, - oneof='one_expression', - message=CaseExpression, - ) - concatenate: ConcatenateExpression = proto.Field( - proto.MESSAGE, - number=6, - oneof='one_expression', - message=ConcatenateExpression, - ) - - -class Metric(proto.Message): - r"""The quantitative measurements of a report. For example, the metric - ``eventCount`` is the total number of events. Requests are allowed - up to 10 metrics. - - Attributes: - name (str): - The name of the metric. See the `API - Metrics `__ - for the list of metric names. - - If ``expression`` is specified, ``name`` can be any string - that you would like within the allowed character set. For - example if ``expression`` is ``screenPageViews/sessions``, - you could call that metric's name = ``viewsPerSession``. - Metric names that you choose must match the regular - expression ``^[a-zA-Z0-9_]$``. - - Metrics are referenced by ``name`` in ``metricFilter``, - ``orderBys``, and metric ``expression``. - expression (str): - A mathematical expression for derived metrics. For example, - the metric Event count per user is - ``eventCount/totalUsers``. - invisible (bool): - Indicates if a metric is invisible in the report response. - If a metric is invisible, the metric will not produce a - column in the response, but can be used in ``metricFilter``, - ``orderBys``, or a metric ``expression``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - expression: str = proto.Field( - proto.STRING, - number=2, - ) - invisible: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class FilterExpression(proto.Message): - r"""To express dimension or metric filters. The fields in the - same FilterExpression 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.data_v1beta.types.FilterExpressionList): - The FilterExpressions in and_group have an AND relationship. - - This field is a member of `oneof`_ ``expr``. - or_group (google.analytics.data_v1beta.types.FilterExpressionList): - The FilterExpressions in or_group have an OR relationship. - - This field is a member of `oneof`_ ``expr``. - not_expression (google.analytics.data_v1beta.types.FilterExpression): - The FilterExpression is NOT of not_expression. - - This field is a member of `oneof`_ ``expr``. - filter (google.analytics.data_v1beta.types.Filter): - 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`_ ``expr``. - """ - - and_group: 'FilterExpressionList' = proto.Field( - proto.MESSAGE, - number=1, - oneof='expr', - message='FilterExpressionList', - ) - or_group: 'FilterExpressionList' = proto.Field( - proto.MESSAGE, - number=2, - oneof='expr', - message='FilterExpressionList', - ) - not_expression: 'FilterExpression' = proto.Field( - proto.MESSAGE, - number=3, - oneof='expr', - message='FilterExpression', - ) - filter: 'Filter' = proto.Field( - proto.MESSAGE, - number=4, - oneof='expr', - message='Filter', - ) - - -class FilterExpressionList(proto.Message): - r"""A list of filter expressions. - - Attributes: - expressions (MutableSequence[google.analytics.data_v1beta.types.FilterExpression]): - A list of filter expressions. - """ - - expressions: MutableSequence['FilterExpression'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='FilterExpression', - ) - - -class Filter(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: - field_name (str): - The dimension name or metric name. - In most methods, dimensions & metrics can be - used for the first time in this field. However - in a RunPivotReportRequest, this field must be - additionally specified by name in the - RunPivotReportRequest's dimensions or metrics. - string_filter (google.analytics.data_v1beta.types.Filter.StringFilter): - Strings related filter. - - This field is a member of `oneof`_ ``one_filter``. - in_list_filter (google.analytics.data_v1beta.types.Filter.InListFilter): - A filter for in list values. - - This field is a member of `oneof`_ ``one_filter``. - numeric_filter (google.analytics.data_v1beta.types.Filter.NumericFilter): - A filter for numeric or date values. - - This field is a member of `oneof`_ ``one_filter``. - between_filter (google.analytics.data_v1beta.types.Filter.BetweenFilter): - A filter for two values. - - This field is a member of `oneof`_ ``one_filter``. - """ - - class StringFilter(proto.Message): - r"""The filter for string - - Attributes: - match_type (google.analytics.data_v1beta.types.Filter.StringFilter.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""" - MATCH_TYPE_UNSPECIFIED = 0 - EXACT = 1 - BEGINS_WITH = 2 - ENDS_WITH = 3 - CONTAINS = 4 - FULL_REGEXP = 5 - PARTIAL_REGEXP = 6 - - match_type: 'Filter.StringFilter.MatchType' = proto.Field( - proto.ENUM, - number=1, - enum='Filter.StringFilter.MatchType', - ) - value: str = proto.Field( - proto.STRING, - number=2, - ) - case_sensitive: bool = proto.Field( - proto.BOOL, - number=3, - ) - - class InListFilter(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 NumericFilter(proto.Message): - r"""Filters for numeric or date values. - - Attributes: - operation (google.analytics.data_v1beta.types.Filter.NumericFilter.Operation): - The operation type for this filter. - value (google.analytics.data_v1beta.types.NumericValue): - A numeric value or a date value. - """ - class Operation(proto.Enum): - r"""The operation applied to a numeric filter""" - OPERATION_UNSPECIFIED = 0 - EQUAL = 1 - LESS_THAN = 2 - LESS_THAN_OR_EQUAL = 3 - GREATER_THAN = 4 - GREATER_THAN_OR_EQUAL = 5 - - operation: 'Filter.NumericFilter.Operation' = proto.Field( - proto.ENUM, - number=1, - enum='Filter.NumericFilter.Operation', - ) - value: 'NumericValue' = proto.Field( - proto.MESSAGE, - number=2, - message='NumericValue', - ) - - class BetweenFilter(proto.Message): - r"""To express that the result needs to be between two numbers - (inclusive). - - Attributes: - from_value (google.analytics.data_v1beta.types.NumericValue): - Begins with this number. - to_value (google.analytics.data_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', - ) - - field_name: str = proto.Field( - proto.STRING, - number=1, - ) - string_filter: StringFilter = proto.Field( - proto.MESSAGE, - number=3, - oneof='one_filter', - message=StringFilter, - ) - in_list_filter: InListFilter = proto.Field( - proto.MESSAGE, - number=4, - oneof='one_filter', - message=InListFilter, - ) - numeric_filter: NumericFilter = proto.Field( - proto.MESSAGE, - number=5, - oneof='one_filter', - message=NumericFilter, - ) - between_filter: BetweenFilter = proto.Field( - proto.MESSAGE, - number=6, - oneof='one_filter', - message=BetweenFilter, - ) - - -class OrderBy(proto.Message): - r"""Order bys define how rows will be sorted in the response. For - example, ordering rows by descending event count is one - ordering, and ordering rows by the event name 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.data_v1beta.types.OrderBy.MetricOrderBy): - Sorts results by a metric's values. - - This field is a member of `oneof`_ ``one_order_by``. - dimension (google.analytics.data_v1beta.types.OrderBy.DimensionOrderBy): - Sorts results by a dimension's values. - - This field is a member of `oneof`_ ``one_order_by``. - pivot (google.analytics.data_v1beta.types.OrderBy.PivotOrderBy): - Sorts results by a metric's values within a - pivot column group. - - This field is a member of `oneof`_ ``one_order_by``. - desc (bool): - If true, sorts by descending 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.data_v1beta.types.OrderBy.DimensionOrderBy.OrderType): - Controls the rule for dimension value - ordering. - """ - class OrderType(proto.Enum): - r"""Rule to order the string dimension values by.""" - ORDER_TYPE_UNSPECIFIED = 0 - ALPHANUMERIC = 1 - CASE_INSENSITIVE_ALPHANUMERIC = 2 - NUMERIC = 3 - - dimension_name: str = proto.Field( - proto.STRING, - number=1, - ) - order_type: 'OrderBy.DimensionOrderBy.OrderType' = proto.Field( - proto.ENUM, - number=2, - enum='OrderBy.DimensionOrderBy.OrderType', - ) - - class PivotOrderBy(proto.Message): - r"""Sorts by a pivot column group. - - Attributes: - metric_name (str): - In the response to order by, order rows by - this column. Must be a metric name from the - request. - pivot_selections (MutableSequence[google.analytics.data_v1beta.types.OrderBy.PivotOrderBy.PivotSelection]): - Used to select a dimension name and value - pivot. If multiple pivot selections are given, - the sort occurs on rows where all pivot - selection dimension name and value pairs match - the row's dimension name and value pair. - """ - - class PivotSelection(proto.Message): - r"""A pair of dimension names and values. Rows with this dimension pivot - pair are ordered by the metric's value. - - For example if pivots = {{"browser", "Chrome"}} and metric_name = - "Sessions", then the rows will be sorted based on Sessions in - Chrome. - - :: - - ---------|----------|----------------|----------|---------------- - | Chrome | Chrome | Safari | Safari - ---------|----------|----------------|----------|---------------- - Country | Sessions | Pages/Sessions | Sessions | Pages/Sessions - ---------|----------|----------------|----------|---------------- - US | 2 | 2 | 3 | 1 - ---------|----------|----------------|----------|---------------- - Canada | 3 | 1 | 4 | 1 - ---------|----------|----------------|----------|---------------- - - Attributes: - dimension_name (str): - Must be a dimension name from the request. - dimension_value (str): - Order by only when the named dimension is - this value. - """ - - dimension_name: str = proto.Field( - proto.STRING, - number=1, - ) - dimension_value: str = proto.Field( - proto.STRING, - number=2, - ) - - metric_name: str = proto.Field( - proto.STRING, - number=1, - ) - pivot_selections: MutableSequence['OrderBy.PivotOrderBy.PivotSelection'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='OrderBy.PivotOrderBy.PivotSelection', - ) - - 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, - ) - pivot: PivotOrderBy = proto.Field( - proto.MESSAGE, - number=3, - oneof='one_order_by', - message=PivotOrderBy, - ) - desc: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class Pivot(proto.Message): - r"""Describes the visible dimension columns and rows in the - report response. - - Attributes: - field_names (MutableSequence[str]): - Dimension names for visible columns in the - report response. Including "dateRange" produces - a date range column; for each row in the - response, dimension values in the date range - column will indicate the corresponding date - range from the request. - order_bys (MutableSequence[google.analytics.data_v1beta.types.OrderBy]): - Specifies how dimensions are ordered in the pivot. In the - first Pivot, the OrderBys determine Row and - PivotDimensionHeader ordering; in subsequent Pivots, the - OrderBys determine only PivotDimensionHeader ordering. - Dimensions specified in these OrderBys must be a subset of - Pivot.field_names. - offset (int): - The row count of the start row. The first row - is counted as row 0. - limit (int): - The number of unique combinations of dimension values to - return in this pivot. The ``limit`` parameter is required. A - ``limit`` of 10,000 is common for single pivot requests. - - The product of the ``limit`` for each ``pivot`` in a - ``RunPivotReportRequest`` must not exceed 100,000. For - example, a two pivot request with ``limit: 1000`` in each - pivot will fail because the product is ``1,000,000``. - metric_aggregations (MutableSequence[google.analytics.data_v1beta.types.MetricAggregation]): - Aggregate the metrics by dimensions in this pivot using the - specified metric_aggregations. - """ - - field_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - order_bys: MutableSequence['OrderBy'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='OrderBy', - ) - offset: int = proto.Field( - proto.INT64, - number=3, - ) - limit: int = proto.Field( - proto.INT64, - number=4, - ) - metric_aggregations: MutableSequence['MetricAggregation'] = proto.RepeatedField( - proto.ENUM, - number=5, - enum='MetricAggregation', - ) - - -class CohortSpec(proto.Message): - r"""The specification of cohorts for a cohort report. - - Cohort reports create a time series of user retention for the - cohort. For example, you could select the cohort of users that were - acquired in the first week of September and follow that cohort for - the next six weeks. Selecting the users acquired in the first week - of September cohort is specified in the ``cohort`` object. Following - that cohort for the next six weeks is specified in the - ``cohortsRange`` object. - - For examples, see `Cohort Report - Examples `__. - - The report response could show a weekly time series where say your - app has retained 60% of this cohort after three weeks and 25% of - this cohort after six weeks. These two percentages can be calculated - by the metric ``cohortActiveUsers/cohortTotalUsers`` and will be - separate rows in the report. - - Attributes: - cohorts (MutableSequence[google.analytics.data_v1beta.types.Cohort]): - Defines the selection criteria to group users - into cohorts. - Most cohort reports define only a single cohort. - If multiple cohorts are specified, each cohort - can be recognized in the report by their name. - cohorts_range (google.analytics.data_v1beta.types.CohortsRange): - Cohort reports follow cohorts over an - extended reporting date range. This range - specifies an offset duration to follow the - cohorts over. - cohort_report_settings (google.analytics.data_v1beta.types.CohortReportSettings): - Optional settings for a cohort report. - """ - - cohorts: MutableSequence['Cohort'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Cohort', - ) - cohorts_range: 'CohortsRange' = proto.Field( - proto.MESSAGE, - number=2, - message='CohortsRange', - ) - cohort_report_settings: 'CohortReportSettings' = proto.Field( - proto.MESSAGE, - number=3, - message='CohortReportSettings', - ) - - -class Cohort(proto.Message): - r"""Defines a cohort selection criteria. A cohort is a group of users - who share a common characteristic. For example, users with the same - ``firstSessionDate`` belong to the same cohort. - - Attributes: - name (str): - Assigns a name to this cohort. The dimension ``cohort`` is - valued to this name in a report response. If set, cannot - begin with ``cohort_`` or ``RESERVED_``. If not set, cohorts - are named by their zero based index ``cohort_0``, - ``cohort_1``, etc. - dimension (str): - Dimension used by the cohort. Required and only supports - ``firstSessionDate``. - date_range (google.analytics.data_v1beta.types.DateRange): - The cohort selects users whose first touch date is between - start date and end date defined in the ``dateRange``. This - ``dateRange`` does not specify the full date range of event - data that is present in a cohort report. In a cohort report, - this ``dateRange`` is extended by the granularity and offset - present in the ``cohortsRange``; event data for the extended - reporting date range is present in a cohort report. - - In a cohort request, this ``dateRange`` is required and the - ``dateRanges`` in the ``RunReportRequest`` or - ``RunPivotReportRequest`` must be unspecified. - - This ``dateRange`` should generally be aligned with the - cohort's granularity. If ``CohortsRange`` uses daily - granularity, this ``dateRange`` can be a single day. If - ``CohortsRange`` uses weekly granularity, this ``dateRange`` - can be aligned to a week boundary, starting at Sunday and - ending Saturday. If ``CohortsRange`` uses monthly - granularity, this ``dateRange`` can be aligned to a month, - starting at the first and ending on the last day of the - month. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - dimension: str = proto.Field( - proto.STRING, - number=2, - ) - date_range: 'DateRange' = proto.Field( - proto.MESSAGE, - number=3, - message='DateRange', - ) - - -class CohortsRange(proto.Message): - r"""Configures the extended reporting date range for a cohort - report. Specifies an offset duration to follow the cohorts over. - - Attributes: - granularity (google.analytics.data_v1beta.types.CohortsRange.Granularity): - Required. The granularity used to interpret the - ``startOffset`` and ``endOffset`` for the extended reporting - date range for a cohort report. - start_offset (int): - ``startOffset`` specifies the start date of the extended - reporting date range for a cohort report. ``startOffset`` is - commonly set to 0 so that reports contain data from the - acquisition of the cohort forward. - - If ``granularity`` is ``DAILY``, the ``startDate`` of the - extended reporting date range is ``startDate`` of the cohort - plus ``startOffset`` days. - - If ``granularity`` is ``WEEKLY``, the ``startDate`` of the - extended reporting date range is ``startDate`` of the cohort - plus ``startOffset * 7`` days. - - If ``granularity`` is ``MONTHLY``, the ``startDate`` of the - extended reporting date range is ``startDate`` of the cohort - plus ``startOffset * 30`` days. - end_offset (int): - Required. ``endOffset`` specifies the end date of the - extended reporting date range for a cohort report. - ``endOffset`` can be any positive integer but is commonly - set to 5 to 10 so that reports contain data on the cohort - for the next several granularity time periods. - - If ``granularity`` is ``DAILY``, the ``endDate`` of the - extended reporting date range is ``endDate`` of the cohort - plus ``endOffset`` days. - - If ``granularity`` is ``WEEKLY``, the ``endDate`` of the - extended reporting date range is ``endDate`` of the cohort - plus ``endOffset * 7`` days. - - If ``granularity`` is ``MONTHLY``, the ``endDate`` of the - extended reporting date range is ``endDate`` of the cohort - plus ``endOffset * 30`` days. - """ - class Granularity(proto.Enum): - r"""The granularity used to interpret the ``startOffset`` and - ``endOffset`` for the extended reporting date range for a cohort - report. - """ - GRANULARITY_UNSPECIFIED = 0 - DAILY = 1 - WEEKLY = 2 - MONTHLY = 3 - - granularity: Granularity = proto.Field( - proto.ENUM, - number=1, - enum=Granularity, - ) - start_offset: int = proto.Field( - proto.INT32, - number=2, - ) - end_offset: int = proto.Field( - proto.INT32, - number=3, - ) - - -class CohortReportSettings(proto.Message): - r"""Optional settings of a cohort report. - - Attributes: - accumulate (bool): - If true, accumulates the result from first touch day to the - end day. Not supported in ``RunReportRequest``. - """ - - accumulate: bool = proto.Field( - proto.BOOL, - number=1, - ) - - -class ResponseMetaData(proto.Message): - r"""Response's metadata carrying additional information about the - report content. - - Attributes: - data_loss_from_other_row (bool): - If true, indicates some buckets of dimension - combinations are rolled into "(other)" row. This - can happen for high cardinality reports. - schema_restriction_response (google.analytics.data_v1beta.types.ResponseMetaData.SchemaRestrictionResponse): - Describes the schema restrictions actively enforced in - creating this report. To learn more, see `Access and - data-restriction - management `__. - - This field is a member of `oneof`_ ``_schema_restriction_response``. - currency_code (str): - The currency code used in this report. Intended to be used - in formatting currency metrics like ``purchaseRevenue`` for - visualization. If currency_code was specified in the - request, this response parameter will echo the request - parameter; otherwise, this response parameter is the - property's current currency_code. - - Currency codes are string encodings of currency types from - the ISO 4217 standard - (https://en.wikipedia.org/wiki/ISO_4217); for example "USD", - "EUR", "JPY". To learn more, see - https://support.google.com/analytics/answer/9796179. - - This field is a member of `oneof`_ ``_currency_code``. - time_zone (str): - The property's current timezone. Intended to be used to - interpret time-based dimensions like ``hour`` and - ``minute``. Formatted as strings from the IANA Time Zone - database (https://www.iana.org/time-zones); for example - "America/New_York" or "Asia/Tokyo". - - This field is a member of `oneof`_ ``_time_zone``. - empty_reason (str): - If empty reason is specified, the report is - empty for this reason. - - This field is a member of `oneof`_ ``_empty_reason``. - subject_to_thresholding (bool): - If ``subjectToThresholding`` is true, this report is subject - to thresholding and only returns data that meets the minimum - aggregation thresholds. It is possible for a request to be - subject to thresholding thresholding and no data is absent - from the report, and this happens when all data is above the - thresholds. To learn more, see `Data - thresholds `__ - and `About Demographics and - Interests `__. - - This field is a member of `oneof`_ ``_subject_to_thresholding``. - """ - - class SchemaRestrictionResponse(proto.Message): - r"""The schema restrictions actively enforced in creating this report. - To learn more, see `Access and data-restriction - management `__. - - Attributes: - active_metric_restrictions (MutableSequence[google.analytics.data_v1beta.types.ResponseMetaData.SchemaRestrictionResponse.ActiveMetricRestriction]): - All restrictions actively enforced in creating the report. - For example, ``purchaseRevenue`` always has the restriction - type ``REVENUE_DATA``. However, this active response - restriction is only populated if the user's custom role - disallows access to ``REVENUE_DATA``. - """ - - class ActiveMetricRestriction(proto.Message): - r"""A metric actively restricted in creating the report. - - Attributes: - metric_name (str): - The name of the restricted metric. - - This field is a member of `oneof`_ ``_metric_name``. - restricted_metric_types (MutableSequence[google.analytics.data_v1beta.types.RestrictedMetricType]): - The reason for this metric's restriction. - """ - - metric_name: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - restricted_metric_types: MutableSequence['RestrictedMetricType'] = proto.RepeatedField( - proto.ENUM, - number=2, - enum='RestrictedMetricType', - ) - - active_metric_restrictions: MutableSequence['ResponseMetaData.SchemaRestrictionResponse.ActiveMetricRestriction'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ResponseMetaData.SchemaRestrictionResponse.ActiveMetricRestriction', - ) - - data_loss_from_other_row: bool = proto.Field( - proto.BOOL, - number=3, - ) - schema_restriction_response: SchemaRestrictionResponse = proto.Field( - proto.MESSAGE, - number=4, - optional=True, - message=SchemaRestrictionResponse, - ) - currency_code: str = proto.Field( - proto.STRING, - number=5, - optional=True, - ) - time_zone: str = proto.Field( - proto.STRING, - number=6, - optional=True, - ) - empty_reason: str = proto.Field( - proto.STRING, - number=7, - optional=True, - ) - subject_to_thresholding: bool = proto.Field( - proto.BOOL, - number=8, - optional=True, - ) - - -class DimensionHeader(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: - name (str): - The dimension's name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class MetricHeader(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: - name (str): - The metric's name. - type_ (google.analytics.data_v1beta.types.MetricType): - The metric's data type. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: 'MetricType' = proto.Field( - proto.ENUM, - number=2, - enum='MetricType', - ) - - -class PivotHeader(proto.Message): - r"""Dimensions' values in a single pivot. - - Attributes: - pivot_dimension_headers (MutableSequence[google.analytics.data_v1beta.types.PivotDimensionHeader]): - The size is the same as the cardinality of - the corresponding dimension combinations. - row_count (int): - The cardinality of the pivot. The total number of rows for - this pivot's fields regardless of how the parameters - ``offset`` and ``limit`` are specified in the request. - """ - - pivot_dimension_headers: MutableSequence['PivotDimensionHeader'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='PivotDimensionHeader', - ) - row_count: int = proto.Field( - proto.INT32, - number=2, - ) - - -class PivotDimensionHeader(proto.Message): - r"""Summarizes dimension values from a row for this pivot. - - Attributes: - dimension_values (MutableSequence[google.analytics.data_v1beta.types.DimensionValue]): - Values of multiple dimensions in a pivot. - """ - - dimension_values: MutableSequence['DimensionValue'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='DimensionValue', - ) - - -class Row(proto.Message): - r"""Report data for each row. For example if RunReportRequest contains: - - .. code:: none - - "dimensions": [ - { - "name": "eventName" - }, - { - "name": "countryId" - } - ], - "metrics": [ - { - "name": "eventCount" - } - ] - - One row with 'in_app_purchase' as the eventName, 'JP' as the - countryId, and 15 as the eventCount, would be: - - .. code:: none - - "dimensionValues": [ - { - "value": "in_app_purchase" - }, - { - "value": "JP" - } - ], - "metricValues": [ - { - "value": "15" - } - ] - - Attributes: - dimension_values (MutableSequence[google.analytics.data_v1beta.types.DimensionValue]): - List of requested dimension values. In a PivotReport, - dimension_values are only listed for dimensions included in - a pivot. - metric_values (MutableSequence[google.analytics.data_v1beta.types.MetricValue]): - List of requested visible metric values. - """ - - dimension_values: MutableSequence['DimensionValue'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='DimensionValue', - ) - metric_values: MutableSequence['MetricValue'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='MetricValue', - ) - - -class DimensionValue(proto.Message): - r"""The value of a dimension. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - value (str): - Value as a string if the dimension type is a - string. - - This field is a member of `oneof`_ ``one_value``. - """ - - value: str = proto.Field( - proto.STRING, - number=1, - oneof='one_value', - ) - - -class MetricValue(proto.Message): - r"""The value of a metric. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - value (str): - Measurement value. See MetricHeader for type. - - This field is a member of `oneof`_ ``one_value``. - """ - - value: str = proto.Field( - proto.STRING, - number=4, - oneof='one_value', - ) - - -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 PropertyQuota(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.data_v1beta.types.QuotaStatus): - Standard Analytics Properties can use up to - 25,000 tokens per day; Analytics 360 Properties - can use 250,000 tokens per day. Most requests - consume fewer than 10 tokens. - tokens_per_hour (google.analytics.data_v1beta.types.QuotaStatus): - Standard Analytics Properties can use up to - 5,000 tokens per hour; Analytics 360 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.data_v1beta.types.QuotaStatus): - Standard Analytics Properties can send up to - 10 concurrent requests; Analytics 360 Properties - can use up to 50 concurrent requests. - server_errors_per_project_per_hour (google.analytics.data_v1beta.types.QuotaStatus): - Standard Analytics Properties and cloud - project pairs can have up to 10 server errors - per hour; Analytics 360 Properties and cloud - project pairs can have up to 50 server errors - per hour. - potentially_thresholded_requests_per_hour (google.analytics.data_v1beta.types.QuotaStatus): - Analytics Properties can send up to 120 - requests with potentially thresholded dimensions - per hour. In a batch request, each report - request is individually counted for this quota - if the request contains potentially thresholded - dimensions. - tokens_per_project_per_hour (google.analytics.data_v1beta.types.QuotaStatus): - Analytics Properties can use up to 25% of - their tokens per project per hour. This amounts - to standard Analytics Properties can use up to - 1,250 tokens per project per hour, and 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: 'QuotaStatus' = proto.Field( - proto.MESSAGE, - number=1, - message='QuotaStatus', - ) - tokens_per_hour: 'QuotaStatus' = proto.Field( - proto.MESSAGE, - number=2, - message='QuotaStatus', - ) - concurrent_requests: 'QuotaStatus' = proto.Field( - proto.MESSAGE, - number=3, - message='QuotaStatus', - ) - server_errors_per_project_per_hour: 'QuotaStatus' = proto.Field( - proto.MESSAGE, - number=4, - message='QuotaStatus', - ) - potentially_thresholded_requests_per_hour: 'QuotaStatus' = proto.Field( - proto.MESSAGE, - number=5, - message='QuotaStatus', - ) - tokens_per_project_per_hour: 'QuotaStatus' = proto.Field( - proto.MESSAGE, - number=6, - message='QuotaStatus', - ) - - -class QuotaStatus(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, - ) - - -class DimensionMetadata(proto.Message): - r"""Explains a dimension. - - Attributes: - api_name (str): - This dimension's name. Useable in - `Dimension <#Dimension>`__'s ``name``. For example, - ``eventName``. - ui_name (str): - This dimension's name within the Google Analytics user - interface. For example, ``Event name``. - description (str): - Description of how this dimension is used and - calculated. - deprecated_api_names (MutableSequence[str]): - Still usable but deprecated names for this dimension. If - populated, this dimension is available by either ``apiName`` - or one of ``deprecatedApiNames`` for a period of time. After - the deprecation period, the dimension will be available only - by ``apiName``. - custom_definition (bool): - True if the dimension is a custom dimension - for this property. - category (str): - The display name of the category that this - dimension belongs to. Similar dimensions and - metrics are categorized together. - """ - - api_name: str = proto.Field( - proto.STRING, - number=1, - ) - ui_name: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - deprecated_api_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - custom_definition: bool = proto.Field( - proto.BOOL, - number=5, - ) - category: str = proto.Field( - proto.STRING, - number=7, - ) - - -class MetricMetadata(proto.Message): - r"""Explains a metric. - - Attributes: - api_name (str): - A metric name. Useable in `Metric <#Metric>`__'s ``name``. - For example, ``eventCount``. - ui_name (str): - This metric's name within the Google Analytics user - interface. For example, ``Event count``. - description (str): - Description of how this metric is used and - calculated. - deprecated_api_names (MutableSequence[str]): - Still usable but deprecated names for this metric. If - populated, this metric is available by either ``apiName`` or - one of ``deprecatedApiNames`` for a period of time. After - the deprecation period, the metric will be available only by - ``apiName``. - type_ (google.analytics.data_v1beta.types.MetricType): - The type of this metric. - expression (str): - The mathematical expression for this derived metric. Can be - used in `Metric <#Metric>`__'s ``expression`` field for - equivalent reports. Most metrics are not expressions, and - for non-expressions, this field is empty. - custom_definition (bool): - True if the metric is a custom metric for - this property. - blocked_reasons (MutableSequence[google.analytics.data_v1beta.types.MetricMetadata.BlockedReason]): - If reasons are specified, your access is blocked to this - metric for this property. API requests from you to this - property for this metric will succeed; however, the report - will contain only zeros for this metric. API requests with - metric filters on blocked metrics will fail. If reasons are - empty, you have access to this metric. - - To learn more, see `Access and data-restriction - management `__. - category (str): - The display name of the category that this - metrics belongs to. Similar dimensions and - metrics are categorized together. - """ - class BlockedReason(proto.Enum): - r"""Justifications for why this metric is blocked.""" - BLOCKED_REASON_UNSPECIFIED = 0 - NO_REVENUE_METRICS = 1 - NO_COST_METRICS = 2 - - api_name: str = proto.Field( - proto.STRING, - number=1, - ) - ui_name: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - deprecated_api_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - type_: 'MetricType' = proto.Field( - proto.ENUM, - number=5, - enum='MetricType', - ) - expression: str = proto.Field( - proto.STRING, - number=6, - ) - custom_definition: bool = proto.Field( - proto.BOOL, - number=7, - ) - blocked_reasons: MutableSequence[BlockedReason] = proto.RepeatedField( - proto.ENUM, - number=8, - enum=BlockedReason, - ) - category: str = proto.Field( - proto.STRING, - number=10, - ) - - -class DimensionCompatibility(proto.Message): - r"""The compatibility for a single dimension. - - Attributes: - dimension_metadata (google.analytics.data_v1beta.types.DimensionMetadata): - The dimension metadata contains the API name - for this compatibility information. The - dimension metadata also contains other helpful - information like the UI name and description. - - This field is a member of `oneof`_ ``_dimension_metadata``. - compatibility (google.analytics.data_v1beta.types.Compatibility): - The compatibility of this dimension. If the - compatibility is COMPATIBLE, this dimension can - be successfully added to the report. - - This field is a member of `oneof`_ ``_compatibility``. - """ - - dimension_metadata: 'DimensionMetadata' = proto.Field( - proto.MESSAGE, - number=1, - optional=True, - message='DimensionMetadata', - ) - compatibility: 'Compatibility' = proto.Field( - proto.ENUM, - number=2, - optional=True, - enum='Compatibility', - ) - - -class MetricCompatibility(proto.Message): - r"""The compatibility for a single metric. - - Attributes: - metric_metadata (google.analytics.data_v1beta.types.MetricMetadata): - The metric metadata contains the API name for - this compatibility information. The metric - metadata also contains other helpful information - like the UI name and description. - - This field is a member of `oneof`_ ``_metric_metadata``. - compatibility (google.analytics.data_v1beta.types.Compatibility): - The compatibility of this metric. If the - compatibility is COMPATIBLE, this metric can be - successfully added to the report. - - This field is a member of `oneof`_ ``_compatibility``. - """ - - metric_metadata: 'MetricMetadata' = proto.Field( - proto.MESSAGE, - number=1, - optional=True, - message='MetricMetadata', - ) - compatibility: 'Compatibility' = proto.Field( - proto.ENUM, - number=2, - optional=True, - enum='Compatibility', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/mypy.ini b/owl-bot-staging/v1beta/mypy.ini deleted file mode 100644 index 574c5ae..0000000 --- a/owl-bot-staging/v1beta/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/v1beta/noxfile.py b/owl-bot-staging/v1beta/noxfile.py deleted file mode 100644 index 4a0d334..0000000 --- a/owl-bot-staging/v1beta/noxfile.py +++ /dev/null @@ -1,179 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.10" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/analytics/data_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.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, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_async.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_async.py deleted file mode 100644 index 7478f56..0000000 --- a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchRunPivotReports -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-data - - -# [START analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 data_v1beta - - -async def sample_batch_run_pivot_reports(): - # Create a client - client = data_v1beta.BetaAnalyticsDataAsyncClient() - - # Initialize request argument(s) - request = data_v1beta.BatchRunPivotReportsRequest( - ) - - # Make the request - response = await client.batch_run_pivot_reports(request=request) - - # Handle the response - print(response) - -# [END analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_sync.py deleted file mode 100644 index e41ff39..0000000 --- a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchRunPivotReports -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-data - - -# [START analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 data_v1beta - - -def sample_batch_run_pivot_reports(): - # Create a client - client = data_v1beta.BetaAnalyticsDataClient() - - # Initialize request argument(s) - request = data_v1beta.BatchRunPivotReportsRequest( - ) - - # Make the request - response = client.batch_run_pivot_reports(request=request) - - # Handle the response - print(response) - -# [END analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_async.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_async.py deleted file mode 100644 index 4d3970d..0000000 --- a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchRunReports -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-data - - -# [START analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunReports_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 data_v1beta - - -async def sample_batch_run_reports(): - # Create a client - client = data_v1beta.BetaAnalyticsDataAsyncClient() - - # Initialize request argument(s) - request = data_v1beta.BatchRunReportsRequest( - ) - - # Make the request - response = await client.batch_run_reports(request=request) - - # Handle the response - print(response) - -# [END analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunReports_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_sync.py deleted file mode 100644 index dd30901..0000000 --- a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchRunReports -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-data - - -# [START analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunReports_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 data_v1beta - - -def sample_batch_run_reports(): - # Create a client - client = data_v1beta.BetaAnalyticsDataClient() - - # Initialize request argument(s) - request = data_v1beta.BatchRunReportsRequest( - ) - - # Make the request - response = client.batch_run_reports(request=request) - - # Handle the response - print(response) - -# [END analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunReports_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_async.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_async.py deleted file mode 100644 index 13ca3bf..0000000 --- a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CheckCompatibility -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-data - - -# [START analyticsdata_v1beta_generated_BetaAnalyticsData_CheckCompatibility_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 data_v1beta - - -async def sample_check_compatibility(): - # Create a client - client = data_v1beta.BetaAnalyticsDataAsyncClient() - - # Initialize request argument(s) - request = data_v1beta.CheckCompatibilityRequest( - ) - - # Make the request - response = await client.check_compatibility(request=request) - - # Handle the response - print(response) - -# [END analyticsdata_v1beta_generated_BetaAnalyticsData_CheckCompatibility_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_sync.py deleted file mode 100644 index b1a62c0..0000000 --- a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CheckCompatibility -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-data - - -# [START analyticsdata_v1beta_generated_BetaAnalyticsData_CheckCompatibility_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 data_v1beta - - -def sample_check_compatibility(): - # Create a client - client = data_v1beta.BetaAnalyticsDataClient() - - # Initialize request argument(s) - request = data_v1beta.CheckCompatibilityRequest( - ) - - # Make the request - response = client.check_compatibility(request=request) - - # Handle the response - print(response) - -# [END analyticsdata_v1beta_generated_BetaAnalyticsData_CheckCompatibility_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_async.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_async.py deleted file mode 100644 index f450aed..0000000 --- a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetMetadata -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-data - - -# [START analyticsdata_v1beta_generated_BetaAnalyticsData_GetMetadata_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 data_v1beta - - -async def sample_get_metadata(): - # Create a client - client = data_v1beta.BetaAnalyticsDataAsyncClient() - - # Initialize request argument(s) - request = data_v1beta.GetMetadataRequest( - name="name_value", - ) - - # Make the request - response = await client.get_metadata(request=request) - - # Handle the response - print(response) - -# [END analyticsdata_v1beta_generated_BetaAnalyticsData_GetMetadata_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_sync.py deleted file mode 100644 index a331017..0000000 --- a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetMetadata -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-data - - -# [START analyticsdata_v1beta_generated_BetaAnalyticsData_GetMetadata_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 data_v1beta - - -def sample_get_metadata(): - # Create a client - client = data_v1beta.BetaAnalyticsDataClient() - - # Initialize request argument(s) - request = data_v1beta.GetMetadataRequest( - name="name_value", - ) - - # Make the request - response = client.get_metadata(request=request) - - # Handle the response - print(response) - -# [END analyticsdata_v1beta_generated_BetaAnalyticsData_GetMetadata_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_async.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_async.py deleted file mode 100644 index 895037a..0000000 --- a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RunPivotReport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-data - - -# [START analyticsdata_v1beta_generated_BetaAnalyticsData_RunPivotReport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 data_v1beta - - -async def sample_run_pivot_report(): - # Create a client - client = data_v1beta.BetaAnalyticsDataAsyncClient() - - # Initialize request argument(s) - request = data_v1beta.RunPivotReportRequest( - ) - - # Make the request - response = await client.run_pivot_report(request=request) - - # Handle the response - print(response) - -# [END analyticsdata_v1beta_generated_BetaAnalyticsData_RunPivotReport_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_sync.py deleted file mode 100644 index 20a0574..0000000 --- a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RunPivotReport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-data - - -# [START analyticsdata_v1beta_generated_BetaAnalyticsData_RunPivotReport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 data_v1beta - - -def sample_run_pivot_report(): - # Create a client - client = data_v1beta.BetaAnalyticsDataClient() - - # Initialize request argument(s) - request = data_v1beta.RunPivotReportRequest( - ) - - # Make the request - response = client.run_pivot_report(request=request) - - # Handle the response - print(response) - -# [END analyticsdata_v1beta_generated_BetaAnalyticsData_RunPivotReport_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_async.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_async.py deleted file mode 100644 index ac1f54d..0000000 --- a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RunRealtimeReport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-data - - -# [START analyticsdata_v1beta_generated_BetaAnalyticsData_RunRealtimeReport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 data_v1beta - - -async def sample_run_realtime_report(): - # Create a client - client = data_v1beta.BetaAnalyticsDataAsyncClient() - - # Initialize request argument(s) - request = data_v1beta.RunRealtimeReportRequest( - ) - - # Make the request - response = await client.run_realtime_report(request=request) - - # Handle the response - print(response) - -# [END analyticsdata_v1beta_generated_BetaAnalyticsData_RunRealtimeReport_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_sync.py deleted file mode 100644 index 5985bb1..0000000 --- a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RunRealtimeReport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-data - - -# [START analyticsdata_v1beta_generated_BetaAnalyticsData_RunRealtimeReport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 data_v1beta - - -def sample_run_realtime_report(): - # Create a client - client = data_v1beta.BetaAnalyticsDataClient() - - # Initialize request argument(s) - request = data_v1beta.RunRealtimeReportRequest( - ) - - # Make the request - response = client.run_realtime_report(request=request) - - # Handle the response - print(response) - -# [END analyticsdata_v1beta_generated_BetaAnalyticsData_RunRealtimeReport_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_report_async.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_report_async.py deleted file mode 100644 index df56098..0000000 --- a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_report_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RunReport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-data - - -# [START analyticsdata_v1beta_generated_BetaAnalyticsData_RunReport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 data_v1beta - - -async def sample_run_report(): - # Create a client - client = data_v1beta.BetaAnalyticsDataAsyncClient() - - # Initialize request argument(s) - request = data_v1beta.RunReportRequest( - ) - - # Make the request - response = await client.run_report(request=request) - - # Handle the response - print(response) - -# [END analyticsdata_v1beta_generated_BetaAnalyticsData_RunReport_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_report_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_report_sync.py deleted file mode 100644 index 4dbf6eb..0000000 --- a/owl-bot-staging/v1beta/samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_run_report_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RunReport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# 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-data - - -# [START analyticsdata_v1beta_generated_BetaAnalyticsData_RunReport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require 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 data_v1beta - - -def sample_run_report(): - # Create a client - client = data_v1beta.BetaAnalyticsDataClient() - - # Initialize request argument(s) - request = data_v1beta.RunReportRequest( - ) - - # Make the request - response = client.run_report(request=request) - - # Handle the response - print(response) - -# [END analyticsdata_v1beta_generated_BetaAnalyticsData_RunReport_sync] diff --git a/owl-bot-staging/v1beta/scripts/fixup_data_v1beta_keywords.py b/owl-bot-staging/v1beta/scripts/fixup_data_v1beta_keywords.py deleted file mode 100644 index 3f3b1da..0000000 --- a/owl-bot-staging/v1beta/scripts/fixup_data_v1beta_keywords.py +++ /dev/null @@ -1,182 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 dataCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_run_pivot_reports': ('property', 'requests', ), - 'batch_run_reports': ('property', 'requests', ), - 'check_compatibility': ('property', 'dimensions', 'metrics', 'dimension_filter', 'metric_filter', 'compatibility_filter', ), - 'get_metadata': ('name', ), - 'run_pivot_report': ('property', 'dimensions', 'metrics', 'date_ranges', 'pivots', 'dimension_filter', 'metric_filter', 'currency_code', 'cohort_spec', 'keep_empty_rows', 'return_property_quota', ), - 'run_realtime_report': ('property', 'dimensions', 'metrics', 'dimension_filter', 'metric_filter', 'limit', 'metric_aggregations', 'order_bys', 'return_property_quota', 'minute_ranges', ), - 'run_report': ('property', 'dimensions', 'metrics', 'date_ranges', 'dimension_filter', 'metric_filter', 'offset', 'limit', 'metric_aggregations', 'order_bys', 'currency_code', 'cohort_spec', 'keep_empty_rows', 'return_property_quota', ), - } - - 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=dataCallTransformer(), -): - """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 data 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/v1beta/setup.py b/owl-bot-staging/v1beta/setup.py deleted file mode 100644 index 6563668..0000000 --- a/owl-bot-staging/v1beta/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-analytics-data' - - -description = "Google Analytics Data API client library" - -version = {} -with open(os.path.join(package_root, 'google/analytics/data/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.33.2, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -url = "https://github.com/googleapis/python-google-analytics-data" - -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.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google"] -if "google.cloud" in packages: - namespaces.append("google.cloud") - -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", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/v1beta/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9ae..0000000 --- a/owl-bot-staging/v1beta/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- 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/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/v1beta/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9ae..0000000 --- a/owl-bot-staging/v1beta/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- 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/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/v1beta/testing/constraints-3.7.txt deleted file mode 100644 index aca9f2d..0000000 --- a/owl-bot-staging/v1beta/testing/constraints-3.7.txt +++ /dev/null @@ -1,11 +0,0 @@ -# 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 -# This file is intentionally left empty to test the -# latest versions of dependencies. -google-api-core==1.33.2 -proto-plus==1.22.0 -protobuf==3.19.5 diff --git a/owl-bot-staging/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/v1beta/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9ae..0000000 --- a/owl-bot-staging/v1beta/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- 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/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/v1beta/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9ae..0000000 --- a/owl-bot-staging/v1beta/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- 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/v1beta/tests/__init__.py b/owl-bot-staging/v1beta/tests/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1beta/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1beta/tests/unit/__init__.py b/owl-bot-staging/v1beta/tests/unit/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1beta/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1beta/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1beta/tests/unit/gapic/data_v1beta/__init__.py b/owl-bot-staging/v1beta/tests/unit/gapic/data_v1beta/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1beta/tests/unit/gapic/data_v1beta/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1beta/tests/unit/gapic/data_v1beta/test_beta_analytics_data.py b/owl-bot-staging/v1beta/tests/unit/gapic/data_v1beta/test_beta_analytics_data.py deleted file mode 100644 index 300141e..0000000 --- a/owl-bot-staging/v1beta/tests/unit/gapic/data_v1beta/test_beta_analytics_data.py +++ /dev/null @@ -1,3230 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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.data_v1beta.services.beta_analytics_data import BetaAnalyticsDataAsyncClient -from google.analytics.data_v1beta.services.beta_analytics_data import BetaAnalyticsDataClient -from google.analytics.data_v1beta.services.beta_analytics_data import transports -from google.analytics.data_v1beta.types import analytics_data_api -from google.analytics.data_v1beta.types import data -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -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 BetaAnalyticsDataClient._get_default_mtls_endpoint(None) is None - assert BetaAnalyticsDataClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert BetaAnalyticsDataClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert BetaAnalyticsDataClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert BetaAnalyticsDataClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert BetaAnalyticsDataClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (BetaAnalyticsDataClient, "grpc"), - (BetaAnalyticsDataAsyncClient, "grpc_asyncio"), - (BetaAnalyticsDataClient, "rest"), -]) -def test_beta_analytics_data_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 == ( - 'analyticsdata.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://analyticsdata.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.BetaAnalyticsDataGrpcTransport, "grpc"), - (transports.BetaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.BetaAnalyticsDataRestTransport, "rest"), -]) -def test_beta_analytics_data_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", [ - (BetaAnalyticsDataClient, "grpc"), - (BetaAnalyticsDataAsyncClient, "grpc_asyncio"), - (BetaAnalyticsDataClient, "rest"), -]) -def test_beta_analytics_data_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 == ( - 'analyticsdata.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://analyticsdata.googleapis.com' - ) - - -def test_beta_analytics_data_client_get_transport_class(): - transport = BetaAnalyticsDataClient.get_transport_class() - available_transports = [ - transports.BetaAnalyticsDataGrpcTransport, - transports.BetaAnalyticsDataRestTransport, - ] - assert transport in available_transports - - transport = BetaAnalyticsDataClient.get_transport_class("grpc") - assert transport == transports.BetaAnalyticsDataGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (BetaAnalyticsDataClient, transports.BetaAnalyticsDataGrpcTransport, "grpc"), - (BetaAnalyticsDataAsyncClient, transports.BetaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio"), - (BetaAnalyticsDataClient, transports.BetaAnalyticsDataRestTransport, "rest"), -]) -@mock.patch.object(BetaAnalyticsDataClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BetaAnalyticsDataClient)) -@mock.patch.object(BetaAnalyticsDataAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BetaAnalyticsDataAsyncClient)) -def test_beta_analytics_data_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(BetaAnalyticsDataClient, '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(BetaAnalyticsDataClient, '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, - 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): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # 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, - 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, - 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", [ - (BetaAnalyticsDataClient, transports.BetaAnalyticsDataGrpcTransport, "grpc", "true"), - (BetaAnalyticsDataAsyncClient, transports.BetaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (BetaAnalyticsDataClient, transports.BetaAnalyticsDataGrpcTransport, "grpc", "false"), - (BetaAnalyticsDataAsyncClient, transports.BetaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (BetaAnalyticsDataClient, transports.BetaAnalyticsDataRestTransport, "rest", "true"), - (BetaAnalyticsDataClient, transports.BetaAnalyticsDataRestTransport, "rest", "false"), -]) -@mock.patch.object(BetaAnalyticsDataClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BetaAnalyticsDataClient)) -@mock.patch.object(BetaAnalyticsDataAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BetaAnalyticsDataAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_beta_analytics_data_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 - 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 - 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, - 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", [ - BetaAnalyticsDataClient, BetaAnalyticsDataAsyncClient -]) -@mock.patch.object(BetaAnalyticsDataClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BetaAnalyticsDataClient)) -@mock.patch.object(BetaAnalyticsDataAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BetaAnalyticsDataAsyncClient)) -def test_beta_analytics_data_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 - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (BetaAnalyticsDataClient, transports.BetaAnalyticsDataGrpcTransport, "grpc"), - (BetaAnalyticsDataAsyncClient, transports.BetaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio"), - (BetaAnalyticsDataClient, transports.BetaAnalyticsDataRestTransport, "rest"), -]) -def test_beta_analytics_data_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, - 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", [ - (BetaAnalyticsDataClient, transports.BetaAnalyticsDataGrpcTransport, "grpc", grpc_helpers), - (BetaAnalyticsDataAsyncClient, transports.BetaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (BetaAnalyticsDataClient, transports.BetaAnalyticsDataRestTransport, "rest", None), -]) -def test_beta_analytics_data_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, - 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_beta_analytics_data_client_client_options_from_dict(): - with mock.patch('google.analytics.data_v1beta.services.beta_analytics_data.transports.BetaAnalyticsDataGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = BetaAnalyticsDataClient( - 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", [ - (BetaAnalyticsDataClient, transports.BetaAnalyticsDataGrpcTransport, "grpc", grpc_helpers), - (BetaAnalyticsDataAsyncClient, transports.BetaAnalyticsDataGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_beta_analytics_data_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, - 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( - "analyticsdata.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/analytics', - 'https://www.googleapis.com/auth/analytics.readonly', -), - scopes=None, - default_host="analyticsdata.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - analytics_data_api.RunReportRequest, - dict, -]) -def test_run_report(request_type, transport: str = 'grpc'): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = analytics_data_api.RunReportResponse( - row_count=992, - kind='kind_value', - ) - response = client.run_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] == analytics_data_api.RunReportRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.RunReportResponse) - assert response.row_count == 992 - assert response.kind == 'kind_value' - - -def test_run_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 = BetaAnalyticsDataClient( - credentials=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_report), - '__call__') as call: - client.run_report() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.RunReportRequest() - -@pytest.mark.asyncio -async def test_run_report_async(transport: str = 'grpc_asyncio', request_type=analytics_data_api.RunReportRequest): - client = BetaAnalyticsDataAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.RunReportResponse( - row_count=992, - kind='kind_value', - )) - response = await client.run_report(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.RunReportRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.RunReportResponse) - assert response.row_count == 992 - assert response.kind == 'kind_value' - - -@pytest.mark.asyncio -async def test_run_report_async_from_dict(): - await test_run_report_async(request_type=dict) - - -def test_run_report_field_headers(): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_data_api.RunReportRequest() - - request.property = 'property_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_report), - '__call__') as call: - call.return_value = analytics_data_api.RunReportResponse() - client.run_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', - 'property=property_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_run_report_field_headers_async(): - client = BetaAnalyticsDataAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_data_api.RunReportRequest() - - request.property = 'property_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_report), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.RunReportResponse()) - await client.run_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', - 'property=property_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - analytics_data_api.RunPivotReportRequest, - dict, -]) -def test_run_pivot_report(request_type, transport: str = 'grpc'): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_pivot_report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = analytics_data_api.RunPivotReportResponse( - kind='kind_value', - ) - response = client.run_pivot_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] == analytics_data_api.RunPivotReportRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.RunPivotReportResponse) - assert response.kind == 'kind_value' - - -def test_run_pivot_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 = BetaAnalyticsDataClient( - credentials=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_pivot_report), - '__call__') as call: - client.run_pivot_report() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.RunPivotReportRequest() - -@pytest.mark.asyncio -async def test_run_pivot_report_async(transport: str = 'grpc_asyncio', request_type=analytics_data_api.RunPivotReportRequest): - client = BetaAnalyticsDataAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_pivot_report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.RunPivotReportResponse( - kind='kind_value', - )) - response = await client.run_pivot_report(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.RunPivotReportRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.RunPivotReportResponse) - assert response.kind == 'kind_value' - - -@pytest.mark.asyncio -async def test_run_pivot_report_async_from_dict(): - await test_run_pivot_report_async(request_type=dict) - - -def test_run_pivot_report_field_headers(): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_data_api.RunPivotReportRequest() - - request.property = 'property_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_pivot_report), - '__call__') as call: - call.return_value = analytics_data_api.RunPivotReportResponse() - client.run_pivot_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', - 'property=property_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_run_pivot_report_field_headers_async(): - client = BetaAnalyticsDataAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_data_api.RunPivotReportRequest() - - request.property = 'property_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_pivot_report), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.RunPivotReportResponse()) - await client.run_pivot_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', - 'property=property_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - analytics_data_api.BatchRunReportsRequest, - dict, -]) -def test_batch_run_reports(request_type, transport: str = 'grpc'): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_run_reports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = analytics_data_api.BatchRunReportsResponse( - kind='kind_value', - ) - response = client.batch_run_reports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.BatchRunReportsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.BatchRunReportsResponse) - assert response.kind == 'kind_value' - - -def test_batch_run_reports_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_run_reports), - '__call__') as call: - client.batch_run_reports() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.BatchRunReportsRequest() - -@pytest.mark.asyncio -async def test_batch_run_reports_async(transport: str = 'grpc_asyncio', request_type=analytics_data_api.BatchRunReportsRequest): - client = BetaAnalyticsDataAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_run_reports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.BatchRunReportsResponse( - kind='kind_value', - )) - response = await client.batch_run_reports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.BatchRunReportsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.BatchRunReportsResponse) - assert response.kind == 'kind_value' - - -@pytest.mark.asyncio -async def test_batch_run_reports_async_from_dict(): - await test_batch_run_reports_async(request_type=dict) - - -def test_batch_run_reports_field_headers(): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_data_api.BatchRunReportsRequest() - - request.property = 'property_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_run_reports), - '__call__') as call: - call.return_value = analytics_data_api.BatchRunReportsResponse() - client.batch_run_reports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_batch_run_reports_field_headers_async(): - client = BetaAnalyticsDataAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_data_api.BatchRunReportsRequest() - - request.property = 'property_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_run_reports), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.BatchRunReportsResponse()) - await client.batch_run_reports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_data_api.BatchRunPivotReportsRequest, - dict, -]) -def test_batch_run_pivot_reports(request_type, transport: str = 'grpc'): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_run_pivot_reports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = analytics_data_api.BatchRunPivotReportsResponse( - kind='kind_value', - ) - response = client.batch_run_pivot_reports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.BatchRunPivotReportsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.BatchRunPivotReportsResponse) - assert response.kind == 'kind_value' - - -def test_batch_run_pivot_reports_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_run_pivot_reports), - '__call__') as call: - client.batch_run_pivot_reports() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.BatchRunPivotReportsRequest() - -@pytest.mark.asyncio -async def test_batch_run_pivot_reports_async(transport: str = 'grpc_asyncio', request_type=analytics_data_api.BatchRunPivotReportsRequest): - client = BetaAnalyticsDataAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_run_pivot_reports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.BatchRunPivotReportsResponse( - kind='kind_value', - )) - response = await client.batch_run_pivot_reports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.BatchRunPivotReportsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.BatchRunPivotReportsResponse) - assert response.kind == 'kind_value' - - -@pytest.mark.asyncio -async def test_batch_run_pivot_reports_async_from_dict(): - await test_batch_run_pivot_reports_async(request_type=dict) - - -def test_batch_run_pivot_reports_field_headers(): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_data_api.BatchRunPivotReportsRequest() - - request.property = 'property_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_run_pivot_reports), - '__call__') as call: - call.return_value = analytics_data_api.BatchRunPivotReportsResponse() - client.batch_run_pivot_reports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_batch_run_pivot_reports_field_headers_async(): - client = BetaAnalyticsDataAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_data_api.BatchRunPivotReportsRequest() - - request.property = 'property_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_run_pivot_reports), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.BatchRunPivotReportsResponse()) - await client.batch_run_pivot_reports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_data_api.GetMetadataRequest, - dict, -]) -def test_get_metadata(request_type, transport: str = 'grpc'): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_metadata), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = analytics_data_api.Metadata( - name='name_value', - ) - response = client.get_metadata(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.GetMetadataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.Metadata) - assert response.name == 'name_value' - - -def test_get_metadata_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = BetaAnalyticsDataClient( - credentials=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_metadata), - '__call__') as call: - client.get_metadata() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.GetMetadataRequest() - -@pytest.mark.asyncio -async def test_get_metadata_async(transport: str = 'grpc_asyncio', request_type=analytics_data_api.GetMetadataRequest): - client = BetaAnalyticsDataAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_metadata), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.Metadata( - name='name_value', - )) - response = await client.get_metadata(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.GetMetadataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.Metadata) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_metadata_async_from_dict(): - await test_get_metadata_async(request_type=dict) - - -def test_get_metadata_field_headers(): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_data_api.GetMetadataRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_metadata), - '__call__') as call: - call.return_value = analytics_data_api.Metadata() - client.get_metadata(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_metadata_field_headers_async(): - client = BetaAnalyticsDataAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_data_api.GetMetadataRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_metadata), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.Metadata()) - await client.get_metadata(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_metadata_flattened(): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_metadata), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = analytics_data_api.Metadata() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_metadata( - name='name_value', - ) - - # Establish that the 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_metadata_flattened_error(): - client = BetaAnalyticsDataClient( - credentials=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_metadata( - analytics_data_api.GetMetadataRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_metadata_flattened_async(): - client = BetaAnalyticsDataAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_metadata), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = analytics_data_api.Metadata() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.Metadata()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_metadata( - name='name_value', - ) - - # Establish that 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_metadata_flattened_error_async(): - client = BetaAnalyticsDataAsyncClient( - credentials=ga_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_metadata( - analytics_data_api.GetMetadataRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - analytics_data_api.RunRealtimeReportRequest, - dict, -]) -def test_run_realtime_report(request_type, transport: str = 'grpc'): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_realtime_report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = analytics_data_api.RunRealtimeReportResponse( - row_count=992, - kind='kind_value', - ) - response = client.run_realtime_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] == analytics_data_api.RunRealtimeReportRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.RunRealtimeReportResponse) - assert response.row_count == 992 - assert response.kind == 'kind_value' - - -def test_run_realtime_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 = BetaAnalyticsDataClient( - credentials=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_realtime_report), - '__call__') as call: - client.run_realtime_report() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.RunRealtimeReportRequest() - -@pytest.mark.asyncio -async def test_run_realtime_report_async(transport: str = 'grpc_asyncio', request_type=analytics_data_api.RunRealtimeReportRequest): - client = BetaAnalyticsDataAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_realtime_report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.RunRealtimeReportResponse( - row_count=992, - kind='kind_value', - )) - response = await client.run_realtime_report(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.RunRealtimeReportRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.RunRealtimeReportResponse) - assert response.row_count == 992 - assert response.kind == 'kind_value' - - -@pytest.mark.asyncio -async def test_run_realtime_report_async_from_dict(): - await test_run_realtime_report_async(request_type=dict) - - -def test_run_realtime_report_field_headers(): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_data_api.RunRealtimeReportRequest() - - request.property = 'property_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_realtime_report), - '__call__') as call: - call.return_value = analytics_data_api.RunRealtimeReportResponse() - client.run_realtime_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', - 'property=property_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_run_realtime_report_field_headers_async(): - client = BetaAnalyticsDataAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_data_api.RunRealtimeReportRequest() - - request.property = 'property_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_realtime_report), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.RunRealtimeReportResponse()) - await client.run_realtime_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', - 'property=property_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - analytics_data_api.CheckCompatibilityRequest, - dict, -]) -def test_check_compatibility(request_type, transport: str = 'grpc'): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_compatibility), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = analytics_data_api.CheckCompatibilityResponse( - ) - response = client.check_compatibility(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.CheckCompatibilityRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.CheckCompatibilityResponse) - - -def test_check_compatibility_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_compatibility), - '__call__') as call: - client.check_compatibility() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.CheckCompatibilityRequest() - -@pytest.mark.asyncio -async def test_check_compatibility_async(transport: str = 'grpc_asyncio', request_type=analytics_data_api.CheckCompatibilityRequest): - client = BetaAnalyticsDataAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_compatibility), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.CheckCompatibilityResponse( - )) - response = await client.check_compatibility(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_data_api.CheckCompatibilityRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.CheckCompatibilityResponse) - - -@pytest.mark.asyncio -async def test_check_compatibility_async_from_dict(): - await test_check_compatibility_async(request_type=dict) - - -def test_check_compatibility_field_headers(): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_data_api.CheckCompatibilityRequest() - - request.property = 'property_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_compatibility), - '__call__') as call: - call.return_value = analytics_data_api.CheckCompatibilityResponse() - client.check_compatibility(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_check_compatibility_field_headers_async(): - client = BetaAnalyticsDataAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_data_api.CheckCompatibilityRequest() - - request.property = 'property_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_compatibility), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_data_api.CheckCompatibilityResponse()) - await client.check_compatibility(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_data_api.RunReportRequest, - dict, -]) -def test_run_report_rest(request_type): - client = BetaAnalyticsDataClient( - 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_data_api.RunReportResponse( - row_count=992, - kind='kind_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = analytics_data_api.RunReportResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.run_report(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.RunReportResponse) - assert response.row_count == 992 - assert response.kind == 'kind_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_run_report_rest_interceptors(null_interceptor): - transport = transports.BetaAnalyticsDataRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BetaAnalyticsDataRestInterceptor(), - ) - client = BetaAnalyticsDataClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "post_run_report") as post, \ - mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "pre_run_report") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_data_api.RunReportRequest.pb(analytics_data_api.RunReportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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_data_api.RunReportResponse.to_json(analytics_data_api.RunReportResponse()) - - request = analytics_data_api.RunReportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = analytics_data_api.RunReportResponse() - - client.run_report(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_run_report_rest_bad_request(transport: str = 'rest', request_type=analytics_data_api.RunReportRequest): - client = BetaAnalyticsDataClient( - 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.run_report(request) - - -def test_run_report_rest_error(): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - analytics_data_api.RunPivotReportRequest, - dict, -]) -def test_run_pivot_report_rest(request_type): - client = BetaAnalyticsDataClient( - 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_data_api.RunPivotReportResponse( - kind='kind_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = analytics_data_api.RunPivotReportResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.run_pivot_report(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.RunPivotReportResponse) - assert response.kind == 'kind_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_run_pivot_report_rest_interceptors(null_interceptor): - transport = transports.BetaAnalyticsDataRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BetaAnalyticsDataRestInterceptor(), - ) - client = BetaAnalyticsDataClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "post_run_pivot_report") as post, \ - mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "pre_run_pivot_report") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_data_api.RunPivotReportRequest.pb(analytics_data_api.RunPivotReportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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_data_api.RunPivotReportResponse.to_json(analytics_data_api.RunPivotReportResponse()) - - request = analytics_data_api.RunPivotReportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = analytics_data_api.RunPivotReportResponse() - - client.run_pivot_report(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_run_pivot_report_rest_bad_request(transport: str = 'rest', request_type=analytics_data_api.RunPivotReportRequest): - client = BetaAnalyticsDataClient( - 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.run_pivot_report(request) - - -def test_run_pivot_report_rest_error(): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - analytics_data_api.BatchRunReportsRequest, - dict, -]) -def test_batch_run_reports_rest(request_type): - client = BetaAnalyticsDataClient( - 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_data_api.BatchRunReportsResponse( - kind='kind_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = analytics_data_api.BatchRunReportsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_run_reports(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.BatchRunReportsResponse) - assert response.kind == 'kind_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_run_reports_rest_interceptors(null_interceptor): - transport = transports.BetaAnalyticsDataRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BetaAnalyticsDataRestInterceptor(), - ) - client = BetaAnalyticsDataClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "post_batch_run_reports") as post, \ - mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "pre_batch_run_reports") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_data_api.BatchRunReportsRequest.pb(analytics_data_api.BatchRunReportsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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_data_api.BatchRunReportsResponse.to_json(analytics_data_api.BatchRunReportsResponse()) - - request = analytics_data_api.BatchRunReportsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = analytics_data_api.BatchRunReportsResponse() - - client.batch_run_reports(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_run_reports_rest_bad_request(transport: str = 'rest', request_type=analytics_data_api.BatchRunReportsRequest): - client = BetaAnalyticsDataClient( - 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.batch_run_reports(request) - - -def test_batch_run_reports_rest_error(): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - analytics_data_api.BatchRunPivotReportsRequest, - dict, -]) -def test_batch_run_pivot_reports_rest(request_type): - client = BetaAnalyticsDataClient( - 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_data_api.BatchRunPivotReportsResponse( - kind='kind_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = analytics_data_api.BatchRunPivotReportsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_run_pivot_reports(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.BatchRunPivotReportsResponse) - assert response.kind == 'kind_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_run_pivot_reports_rest_interceptors(null_interceptor): - transport = transports.BetaAnalyticsDataRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BetaAnalyticsDataRestInterceptor(), - ) - client = BetaAnalyticsDataClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "post_batch_run_pivot_reports") as post, \ - mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "pre_batch_run_pivot_reports") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_data_api.BatchRunPivotReportsRequest.pb(analytics_data_api.BatchRunPivotReportsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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_data_api.BatchRunPivotReportsResponse.to_json(analytics_data_api.BatchRunPivotReportsResponse()) - - request = analytics_data_api.BatchRunPivotReportsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = analytics_data_api.BatchRunPivotReportsResponse() - - client.batch_run_pivot_reports(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_run_pivot_reports_rest_bad_request(transport: str = 'rest', request_type=analytics_data_api.BatchRunPivotReportsRequest): - client = BetaAnalyticsDataClient( - 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.batch_run_pivot_reports(request) - - -def test_batch_run_pivot_reports_rest_error(): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - analytics_data_api.GetMetadataRequest, - dict, -]) -def test_get_metadata_rest(request_type): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'properties/sample1/metadata'} - request = request_type(**request_init) - - # Mock the http request call within the method and 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_data_api.Metadata( - name='name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = analytics_data_api.Metadata.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_metadata(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.Metadata) - assert response.name == 'name_value' - - -def test_get_metadata_rest_required_fields(request_type=analytics_data_api.GetMetadataRequest): - transport_class = transports.BetaAnalyticsDataRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_metadata._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_metadata._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 = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = analytics_data_api.Metadata() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 - - pb_return_value = analytics_data_api.Metadata.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_metadata(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_metadata_rest_unset_required_fields(): - transport = transports.BetaAnalyticsDataRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_metadata._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_metadata_rest_interceptors(null_interceptor): - transport = transports.BetaAnalyticsDataRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BetaAnalyticsDataRestInterceptor(), - ) - client = BetaAnalyticsDataClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "post_get_metadata") as post, \ - mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "pre_get_metadata") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_data_api.GetMetadataRequest.pb(analytics_data_api.GetMetadataRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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_data_api.Metadata.to_json(analytics_data_api.Metadata()) - - request = analytics_data_api.GetMetadataRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = analytics_data_api.Metadata() - - client.get_metadata(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_metadata_rest_bad_request(transport: str = 'rest', request_type=analytics_data_api.GetMetadataRequest): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'properties/sample1/metadata'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the 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_metadata(request) - - -def test_get_metadata_rest_flattened(): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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_data_api.Metadata() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'properties/sample1/metadata'} - - # 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 - pb_return_value = analytics_data_api.Metadata.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_metadata(**mock_args) - - # Establish that the underlying call 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/*/metadata}" % client.transport._host, args[1]) - - -def test_get_metadata_rest_flattened_error(transport: str = 'rest'): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.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_metadata( - analytics_data_api.GetMetadataRequest(), - name='name_value', - ) - - -def test_get_metadata_rest_error(): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - analytics_data_api.RunRealtimeReportRequest, - dict, -]) -def test_run_realtime_report_rest(request_type): - client = BetaAnalyticsDataClient( - 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_data_api.RunRealtimeReportResponse( - row_count=992, - kind='kind_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = analytics_data_api.RunRealtimeReportResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.run_realtime_report(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.RunRealtimeReportResponse) - assert response.row_count == 992 - assert response.kind == 'kind_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_run_realtime_report_rest_interceptors(null_interceptor): - transport = transports.BetaAnalyticsDataRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BetaAnalyticsDataRestInterceptor(), - ) - client = BetaAnalyticsDataClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "post_run_realtime_report") as post, \ - mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "pre_run_realtime_report") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_data_api.RunRealtimeReportRequest.pb(analytics_data_api.RunRealtimeReportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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_data_api.RunRealtimeReportResponse.to_json(analytics_data_api.RunRealtimeReportResponse()) - - request = analytics_data_api.RunRealtimeReportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = analytics_data_api.RunRealtimeReportResponse() - - client.run_realtime_report(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_run_realtime_report_rest_bad_request(transport: str = 'rest', request_type=analytics_data_api.RunRealtimeReportRequest): - client = BetaAnalyticsDataClient( - 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.run_realtime_report(request) - - -def test_run_realtime_report_rest_error(): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - analytics_data_api.CheckCompatibilityRequest, - dict, -]) -def test_check_compatibility_rest(request_type): - client = BetaAnalyticsDataClient( - 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_data_api.CheckCompatibilityResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = analytics_data_api.CheckCompatibilityResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.check_compatibility(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_data_api.CheckCompatibilityResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_check_compatibility_rest_interceptors(null_interceptor): - transport = transports.BetaAnalyticsDataRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BetaAnalyticsDataRestInterceptor(), - ) - client = BetaAnalyticsDataClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "post_check_compatibility") as post, \ - mock.patch.object(transports.BetaAnalyticsDataRestInterceptor, "pre_check_compatibility") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_data_api.CheckCompatibilityRequest.pb(analytics_data_api.CheckCompatibilityRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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_data_api.CheckCompatibilityResponse.to_json(analytics_data_api.CheckCompatibilityResponse()) - - request = analytics_data_api.CheckCompatibilityRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = analytics_data_api.CheckCompatibilityResponse() - - client.check_compatibility(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_check_compatibility_rest_bad_request(transport: str = 'rest', request_type=analytics_data_api.CheckCompatibilityRequest): - client = BetaAnalyticsDataClient( - 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.check_compatibility(request) - - -def test_check_compatibility_rest_error(): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.BetaAnalyticsDataGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.BetaAnalyticsDataGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = BetaAnalyticsDataClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.BetaAnalyticsDataGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = BetaAnalyticsDataClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = BetaAnalyticsDataClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.BetaAnalyticsDataGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = BetaAnalyticsDataClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.BetaAnalyticsDataGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = BetaAnalyticsDataClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.BetaAnalyticsDataGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.BetaAnalyticsDataGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.BetaAnalyticsDataGrpcTransport, - transports.BetaAnalyticsDataGrpcAsyncIOTransport, - transports.BetaAnalyticsDataRestTransport, -]) -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 = BetaAnalyticsDataClient.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 = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.BetaAnalyticsDataGrpcTransport, - ) - -def test_beta_analytics_data_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.BetaAnalyticsDataTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_beta_analytics_data_base_transport(): - # Instantiate the base transport. - with mock.patch('google.analytics.data_v1beta.services.beta_analytics_data.transports.BetaAnalyticsDataTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.BetaAnalyticsDataTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'run_report', - 'run_pivot_report', - 'batch_run_reports', - 'batch_run_pivot_reports', - 'get_metadata', - 'run_realtime_report', - 'check_compatibility', - ) - 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_beta_analytics_data_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.data_v1beta.services.beta_analytics_data.transports.BetaAnalyticsDataTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.BetaAnalyticsDataTransport( - 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', - 'https://www.googleapis.com/auth/analytics.readonly', -), - quota_project_id="octopus", - ) - - -def test_beta_analytics_data_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.data_v1beta.services.beta_analytics_data.transports.BetaAnalyticsDataTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.BetaAnalyticsDataTransport() - adc.assert_called_once() - - -def test_beta_analytics_data_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) - BetaAnalyticsDataClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/analytics', - 'https://www.googleapis.com/auth/analytics.readonly', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.BetaAnalyticsDataGrpcTransport, - transports.BetaAnalyticsDataGrpcAsyncIOTransport, - ], -) -def test_beta_analytics_data_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', 'https://www.googleapis.com/auth/analytics.readonly',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.BetaAnalyticsDataGrpcTransport, - transports.BetaAnalyticsDataGrpcAsyncIOTransport, - transports.BetaAnalyticsDataRestTransport, - ], -) -def test_beta_analytics_data_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.BetaAnalyticsDataGrpcTransport, grpc_helpers), - (transports.BetaAnalyticsDataGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_beta_analytics_data_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( - "analyticsdata.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/analytics', - 'https://www.googleapis.com/auth/analytics.readonly', -), - scopes=["1", "2"], - default_host="analyticsdata.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.BetaAnalyticsDataGrpcTransport, transports.BetaAnalyticsDataGrpcAsyncIOTransport]) -def test_beta_analytics_data_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_beta_analytics_data_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.BetaAnalyticsDataRestTransport ( - 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_beta_analytics_data_host_no_port(transport_name): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='analyticsdata.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'analyticsdata.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://analyticsdata.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_beta_analytics_data_host_with_port(transport_name): - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='analyticsdata.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'analyticsdata.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://analyticsdata.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_beta_analytics_data_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = BetaAnalyticsDataClient( - credentials=creds1, - transport=transport_name, - ) - client2 = BetaAnalyticsDataClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.run_report._session - session2 = client2.transport.run_report._session - assert session1 != session2 - session1 = client1.transport.run_pivot_report._session - session2 = client2.transport.run_pivot_report._session - assert session1 != session2 - session1 = client1.transport.batch_run_reports._session - session2 = client2.transport.batch_run_reports._session - assert session1 != session2 - session1 = client1.transport.batch_run_pivot_reports._session - session2 = client2.transport.batch_run_pivot_reports._session - assert session1 != session2 - session1 = client1.transport.get_metadata._session - session2 = client2.transport.get_metadata._session - assert session1 != session2 - session1 = client1.transport.run_realtime_report._session - session2 = client2.transport.run_realtime_report._session - assert session1 != session2 - session1 = client1.transport.check_compatibility._session - session2 = client2.transport.check_compatibility._session - assert session1 != session2 -def test_beta_analytics_data_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.BetaAnalyticsDataGrpcTransport( - 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_beta_analytics_data_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.BetaAnalyticsDataGrpcAsyncIOTransport( - 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.BetaAnalyticsDataGrpcTransport, transports.BetaAnalyticsDataGrpcAsyncIOTransport]) -def test_beta_analytics_data_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.BetaAnalyticsDataGrpcTransport, transports.BetaAnalyticsDataGrpcAsyncIOTransport]) -def test_beta_analytics_data_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_metadata_path(): - property = "squid" - expected = "properties/{property}/metadata".format(property=property, ) - actual = BetaAnalyticsDataClient.metadata_path(property) - assert expected == actual - - -def test_parse_metadata_path(): - expected = { - "property": "clam", - } - path = BetaAnalyticsDataClient.metadata_path(**expected) - - # Check that the path construction is reversible. - actual = BetaAnalyticsDataClient.parse_metadata_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = BetaAnalyticsDataClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = BetaAnalyticsDataClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = BetaAnalyticsDataClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = BetaAnalyticsDataClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = BetaAnalyticsDataClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = BetaAnalyticsDataClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = BetaAnalyticsDataClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = BetaAnalyticsDataClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = BetaAnalyticsDataClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = BetaAnalyticsDataClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = BetaAnalyticsDataClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = BetaAnalyticsDataClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = BetaAnalyticsDataClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = BetaAnalyticsDataClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = BetaAnalyticsDataClient.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.BetaAnalyticsDataTransport, '_prep_wrapped_messages') as prep: - client = BetaAnalyticsDataClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.BetaAnalyticsDataTransport, '_prep_wrapped_messages') as prep: - transport_class = BetaAnalyticsDataClient.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 = BetaAnalyticsDataAsyncClient( - 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 = BetaAnalyticsDataClient( - 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 = BetaAnalyticsDataClient( - 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", [ - (BetaAnalyticsDataClient, transports.BetaAnalyticsDataGrpcTransport), - (BetaAnalyticsDataAsyncClient, transports.BetaAnalyticsDataGrpcAsyncIOTransport), -]) -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, - 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/samples/generated_samples/snippet_metadata_data_v1alpha.json b/samples/generated_samples/snippet_metadata_data_v1alpha.json deleted file mode 100644 index fc2b532..0000000 --- a/samples/generated_samples/snippet_metadata_data_v1alpha.json +++ /dev/null @@ -1,167 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.analytics.data.v1alpha", - "version": "v1alpha" - } - ], - "language": "PYTHON", - "name": "google-analytics-data" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.analytics.data_v1alpha.AlphaAnalyticsDataAsyncClient", - "shortName": "AlphaAnalyticsDataAsyncClient" - }, - "fullName": "google.analytics.data_v1alpha.AlphaAnalyticsDataAsyncClient.run_funnel_report", - "method": { - "fullName": "google.analytics.data.v1alpha.AlphaAnalyticsData.RunFunnelReport", - "service": { - "fullName": "google.analytics.data.v1alpha.AlphaAnalyticsData", - "shortName": "AlphaAnalyticsData" - }, - "shortName": "RunFunnelReport" - }, - "parameters": [ - { - "name": "request", - "type": "google.analytics.data_v1alpha.types.RunFunnelReportRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.analytics.data_v1alpha.types.RunFunnelReportResponse", - "shortName": "run_funnel_report" - }, - "description": "Sample for RunFunnelReport", - "file": "analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "analyticsdata_v1alpha_generated_AlphaAnalyticsData_RunFunnelReport_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": "analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.analytics.data_v1alpha.AlphaAnalyticsDataClient", - "shortName": "AlphaAnalyticsDataClient" - }, - "fullName": "google.analytics.data_v1alpha.AlphaAnalyticsDataClient.run_funnel_report", - "method": { - "fullName": "google.analytics.data.v1alpha.AlphaAnalyticsData.RunFunnelReport", - "service": { - "fullName": "google.analytics.data.v1alpha.AlphaAnalyticsData", - "shortName": "AlphaAnalyticsData" - }, - "shortName": "RunFunnelReport" - }, - "parameters": [ - { - "name": "request", - "type": "google.analytics.data_v1alpha.types.RunFunnelReportRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.analytics.data_v1alpha.types.RunFunnelReportResponse", - "shortName": "run_funnel_report" - }, - "description": "Sample for RunFunnelReport", - "file": "analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "analyticsdata_v1alpha_generated_AlphaAnalyticsData_RunFunnelReport_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": "analyticsdata_v1alpha_generated_alpha_analytics_data_run_funnel_report_sync.py" - } - ] -} diff --git a/samples/generated_samples/snippet_metadata_data_v1beta.json b/samples/generated_samples/snippet_metadata_data_v1beta.json deleted file mode 100644 index 4e33261..0000000 --- a/samples/generated_samples/snippet_metadata_data_v1beta.json +++ /dev/null @@ -1,1093 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.analytics.data.v1beta", - "version": "v1beta" - } - ], - "language": "PYTHON", - "name": "google-analytics-data" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient", - "shortName": "BetaAnalyticsDataAsyncClient" - }, - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient.batch_run_pivot_reports", - "method": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.BatchRunPivotReports", - "service": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", - "shortName": "BetaAnalyticsData" - }, - "shortName": "BatchRunPivotReports" - }, - "parameters": [ - { - "name": "request", - "type": "google.analytics.data_v1beta.types.BatchRunPivotReportsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.analytics.data_v1beta.types.BatchRunPivotReportsResponse", - "shortName": "batch_run_pivot_reports" - }, - "description": "Sample for BatchRunPivotReports", - "file": "analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_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": "analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient", - "shortName": "BetaAnalyticsDataClient" - }, - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient.batch_run_pivot_reports", - "method": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.BatchRunPivotReports", - "service": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", - "shortName": "BetaAnalyticsData" - }, - "shortName": "BatchRunPivotReports" - }, - "parameters": [ - { - "name": "request", - "type": "google.analytics.data_v1beta.types.BatchRunPivotReportsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.analytics.data_v1beta.types.BatchRunPivotReportsResponse", - "shortName": "batch_run_pivot_reports" - }, - "description": "Sample for BatchRunPivotReports", - "file": "analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_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": "analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient", - "shortName": "BetaAnalyticsDataAsyncClient" - }, - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient.batch_run_reports", - "method": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.BatchRunReports", - "service": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", - "shortName": "BetaAnalyticsData" - }, - "shortName": "BatchRunReports" - }, - "parameters": [ - { - "name": "request", - "type": "google.analytics.data_v1beta.types.BatchRunReportsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.analytics.data_v1beta.types.BatchRunReportsResponse", - "shortName": "batch_run_reports" - }, - "description": "Sample for BatchRunReports", - "file": "analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunReports_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": "analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient", - "shortName": "BetaAnalyticsDataClient" - }, - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient.batch_run_reports", - "method": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.BatchRunReports", - "service": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", - "shortName": "BetaAnalyticsData" - }, - "shortName": "BatchRunReports" - }, - "parameters": [ - { - "name": "request", - "type": "google.analytics.data_v1beta.types.BatchRunReportsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.analytics.data_v1beta.types.BatchRunReportsResponse", - "shortName": "batch_run_reports" - }, - "description": "Sample for BatchRunReports", - "file": "analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunReports_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": "analyticsdata_v1beta_generated_beta_analytics_data_batch_run_reports_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient", - "shortName": "BetaAnalyticsDataAsyncClient" - }, - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient.check_compatibility", - "method": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.CheckCompatibility", - "service": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", - "shortName": "BetaAnalyticsData" - }, - "shortName": "CheckCompatibility" - }, - "parameters": [ - { - "name": "request", - "type": "google.analytics.data_v1beta.types.CheckCompatibilityRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.analytics.data_v1beta.types.CheckCompatibilityResponse", - "shortName": "check_compatibility" - }, - "description": "Sample for CheckCompatibility", - "file": "analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_CheckCompatibility_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": "analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient", - "shortName": "BetaAnalyticsDataClient" - }, - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient.check_compatibility", - "method": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.CheckCompatibility", - "service": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", - "shortName": "BetaAnalyticsData" - }, - "shortName": "CheckCompatibility" - }, - "parameters": [ - { - "name": "request", - "type": "google.analytics.data_v1beta.types.CheckCompatibilityRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.analytics.data_v1beta.types.CheckCompatibilityResponse", - "shortName": "check_compatibility" - }, - "description": "Sample for CheckCompatibility", - "file": "analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_CheckCompatibility_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": "analyticsdata_v1beta_generated_beta_analytics_data_check_compatibility_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient", - "shortName": "BetaAnalyticsDataAsyncClient" - }, - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient.get_metadata", - "method": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.GetMetadata", - "service": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", - "shortName": "BetaAnalyticsData" - }, - "shortName": "GetMetadata" - }, - "parameters": [ - { - "name": "request", - "type": "google.analytics.data_v1beta.types.GetMetadataRequest" - }, - { - "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.data_v1beta.types.Metadata", - "shortName": "get_metadata" - }, - "description": "Sample for GetMetadata", - "file": "analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_GetMetadata_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": "analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient", - "shortName": "BetaAnalyticsDataClient" - }, - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient.get_metadata", - "method": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.GetMetadata", - "service": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", - "shortName": "BetaAnalyticsData" - }, - "shortName": "GetMetadata" - }, - "parameters": [ - { - "name": "request", - "type": "google.analytics.data_v1beta.types.GetMetadataRequest" - }, - { - "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.data_v1beta.types.Metadata", - "shortName": "get_metadata" - }, - "description": "Sample for GetMetadata", - "file": "analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_GetMetadata_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": "analyticsdata_v1beta_generated_beta_analytics_data_get_metadata_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient", - "shortName": "BetaAnalyticsDataAsyncClient" - }, - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient.run_pivot_report", - "method": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.RunPivotReport", - "service": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", - "shortName": "BetaAnalyticsData" - }, - "shortName": "RunPivotReport" - }, - "parameters": [ - { - "name": "request", - "type": "google.analytics.data_v1beta.types.RunPivotReportRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.analytics.data_v1beta.types.RunPivotReportResponse", - "shortName": "run_pivot_report" - }, - "description": "Sample for RunPivotReport", - "file": "analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_RunPivotReport_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": "analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient", - "shortName": "BetaAnalyticsDataClient" - }, - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient.run_pivot_report", - "method": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.RunPivotReport", - "service": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", - "shortName": "BetaAnalyticsData" - }, - "shortName": "RunPivotReport" - }, - "parameters": [ - { - "name": "request", - "type": "google.analytics.data_v1beta.types.RunPivotReportRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.analytics.data_v1beta.types.RunPivotReportResponse", - "shortName": "run_pivot_report" - }, - "description": "Sample for RunPivotReport", - "file": "analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_RunPivotReport_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": "analyticsdata_v1beta_generated_beta_analytics_data_run_pivot_report_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient", - "shortName": "BetaAnalyticsDataAsyncClient" - }, - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient.run_realtime_report", - "method": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.RunRealtimeReport", - "service": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", - "shortName": "BetaAnalyticsData" - }, - "shortName": "RunRealtimeReport" - }, - "parameters": [ - { - "name": "request", - "type": "google.analytics.data_v1beta.types.RunRealtimeReportRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.analytics.data_v1beta.types.RunRealtimeReportResponse", - "shortName": "run_realtime_report" - }, - "description": "Sample for RunRealtimeReport", - "file": "analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_RunRealtimeReport_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": "analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient", - "shortName": "BetaAnalyticsDataClient" - }, - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient.run_realtime_report", - "method": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.RunRealtimeReport", - "service": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", - "shortName": "BetaAnalyticsData" - }, - "shortName": "RunRealtimeReport" - }, - "parameters": [ - { - "name": "request", - "type": "google.analytics.data_v1beta.types.RunRealtimeReportRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.analytics.data_v1beta.types.RunRealtimeReportResponse", - "shortName": "run_realtime_report" - }, - "description": "Sample for RunRealtimeReport", - "file": "analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_RunRealtimeReport_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": "analyticsdata_v1beta_generated_beta_analytics_data_run_realtime_report_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient", - "shortName": "BetaAnalyticsDataAsyncClient" - }, - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataAsyncClient.run_report", - "method": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.RunReport", - "service": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", - "shortName": "BetaAnalyticsData" - }, - "shortName": "RunReport" - }, - "parameters": [ - { - "name": "request", - "type": "google.analytics.data_v1beta.types.RunReportRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.analytics.data_v1beta.types.RunReportResponse", - "shortName": "run_report" - }, - "description": "Sample for RunReport", - "file": "analyticsdata_v1beta_generated_beta_analytics_data_run_report_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_RunReport_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": "analyticsdata_v1beta_generated_beta_analytics_data_run_report_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient", - "shortName": "BetaAnalyticsDataClient" - }, - "fullName": "google.analytics.data_v1beta.BetaAnalyticsDataClient.run_report", - "method": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData.RunReport", - "service": { - "fullName": "google.analytics.data.v1beta.BetaAnalyticsData", - "shortName": "BetaAnalyticsData" - }, - "shortName": "RunReport" - }, - "parameters": [ - { - "name": "request", - "type": "google.analytics.data_v1beta.types.RunReportRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.analytics.data_v1beta.types.RunReportResponse", - "shortName": "run_report" - }, - "description": "Sample for RunReport", - "file": "analyticsdata_v1beta_generated_beta_analytics_data_run_report_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "analyticsdata_v1beta_generated_BetaAnalyticsData_RunReport_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": "analyticsdata_v1beta_generated_beta_analytics_data_run_report_sync.py" - } - ] -} diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json b/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json similarity index 100% rename from owl-bot-staging/v1alpha/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json rename to samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json diff --git a/owl-bot-staging/v1beta/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json b/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json similarity index 100% rename from owl-bot-staging/v1beta/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json rename to samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json diff --git a/setup.py b/setup.py index ea7b351..10d156b 100644 --- a/setup.py +++ b/setup.py @@ -40,7 +40,7 @@ "proto-plus >= 1.22.0, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] -url = "https://github.com/googleapis/python-analytics-data" +url = "https://github.com/googleapis/python-google-analytics-data" package_root = os.path.abspath(os.path.dirname(__file__)) From e31f0c74624e91069bea2ae9ae2d801bceaef470 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Fri, 11 Nov 2022 14:28:04 -0500 Subject: [PATCH 3/5] fix docs build --- docs/data_v1alpha/types.rst | 1 - docs/data_v1beta/types.rst | 1 - 2 files changed, 2 deletions(-) diff --git a/docs/data_v1alpha/types.rst b/docs/data_v1alpha/types.rst index 8498253..c0378d5 100644 --- a/docs/data_v1alpha/types.rst +++ b/docs/data_v1alpha/types.rst @@ -3,5 +3,4 @@ Types for Google Analytics Data v1alpha API .. automodule:: google.analytics.data_v1alpha.types :members: - :undoc-members: :show-inheritance: diff --git a/docs/data_v1beta/types.rst b/docs/data_v1beta/types.rst index e7db7e0..2d6bf68 100644 --- a/docs/data_v1beta/types.rst +++ b/docs/data_v1beta/types.rst @@ -3,5 +3,4 @@ Types for Google Analytics Data v1beta API .. automodule:: google.analytics.data_v1beta.types :members: - :undoc-members: :show-inheritance: From 45acf3b94a96a0bd445e5b557153c98c64da299b Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Fri, 11 Nov 2022 15:16:34 -0500 Subject: [PATCH 4/5] fix repo url in setup.py --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 10d156b..ea7b351 100644 --- a/setup.py +++ b/setup.py @@ -40,7 +40,7 @@ "proto-plus >= 1.22.0, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] -url = "https://github.com/googleapis/python-google-analytics-data" +url = "https://github.com/googleapis/python-analytics-data" package_root = os.path.abspath(os.path.dirname(__file__)) From 3fdf17ff6e40924d24ce36ec1f17994027a83d9c Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Sat, 12 Nov 2022 13:03:13 +0000 Subject: [PATCH 5/5] update path to snippet metadata json --- release-please-config.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/release-please-config.json b/release-please-config.json index b2a4730..5565177 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -7,12 +7,12 @@ "google/analytics/data/gapic_version.py", { "type": "json", - "path": "samples/generated_samples/snippet_metadata_data_v1alpha.json", + "path": "samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json", "jsonpath": "$.clientLibrary.version" }, { "type": "json", - "path": "samples/generated_samples/snippet_metadata_data_v1beta.json", + "path": "samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json", "jsonpath": "$.clientLibrary.version" } ]