From 9f79f51a17b43f7098e403f5fe2e982b5fa78d70 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 10 Aug 2023 20:52:59 +0000 Subject: [PATCH 1/2] docs: Add link to documentation for ReportConfig proto fields PiperOrigin-RevId: 555577242 Source-Link: https://github.com/googleapis/googleapis/commit/b691174abb7190d187238b62d57996b67a0da7c0 Source-Link: https://github.com/googleapis/googleapis-gen/commit/3dea718c2ec1e14416603709d3cf72c0d691b1d1 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLXN0b3JhZ2VpbnNpZ2h0cy8uT3dsQm90LnlhbWwiLCJoIjoiM2RlYTcxOGMyZWMxZTE0NDE2NjAzNzA5ZDNjZjcyYzBkNjkxYjFkMSJ9 --- .../v1/.coveragerc | 13 + .../google-cloud-storageinsights/v1/.flake8 | 33 + .../v1/MANIFEST.in | 2 + .../v1/README.rst | 49 + .../v1/docs/conf.py | 376 + .../v1/docs/index.rst | 7 + .../v1/docs/storageinsights_v1/services.rst | 6 + .../storageinsights_v1/storage_insights.rst | 10 + .../v1/docs/storageinsights_v1/types.rst | 6 + .../google/cloud/storageinsights/__init__.py | 63 + .../cloud/storageinsights/gapic_version.py | 16 + .../v1/google/cloud/storageinsights/py.typed | 2 + .../cloud/storageinsights_v1/__init__.py | 64 + .../storageinsights_v1/gapic_metadata.json | 133 + .../cloud/storageinsights_v1/gapic_version.py | 16 + .../google/cloud/storageinsights_v1/py.typed | 2 + .../storageinsights_v1/services/__init__.py | 15 + .../services/storage_insights/__init__.py | 22 + .../services/storage_insights/async_client.py | 1277 ++++ .../services/storage_insights/client.py | 1461 ++++ .../services/storage_insights/pagers.py | 260 + .../storage_insights/transports/__init__.py | 38 + .../storage_insights/transports/base.py | 311 + .../storage_insights/transports/grpc.py | 532 ++ .../transports/grpc_asyncio.py | 531 ++ .../storage_insights/transports/rest.py | 1475 ++++ .../storageinsights_v1/types/__init__.py | 56 + .../types/storageinsights.py | 764 ++ .../google-cloud-storageinsights/v1/mypy.ini | 3 + .../v1/noxfile.py | 184 + ...adata_google.cloud.storageinsights.v1.json | 1152 ++++ ...age_insights_create_report_config_async.py | 52 + ...rage_insights_create_report_config_sync.py | 52 + ...age_insights_delete_report_config_async.py | 50 + ...rage_insights_delete_report_config_sync.py | 50 + ...torage_insights_get_report_config_async.py | 52 + ...storage_insights_get_report_config_sync.py | 52 + ...torage_insights_get_report_detail_async.py | 52 + ...storage_insights_get_report_detail_sync.py | 52 + ...rage_insights_list_report_configs_async.py | 53 + ...orage_insights_list_report_configs_sync.py | 53 + ...rage_insights_list_report_details_async.py | 53 + ...orage_insights_list_report_details_sync.py | 53 + ...age_insights_update_report_config_async.py | 51 + ...rage_insights_update_report_config_sync.py | 51 + .../fixup_storageinsights_v1_keywords.py | 182 + .../google-cloud-storageinsights/v1/setup.py | 90 + .../v1/testing/constraints-3.10.txt | 6 + .../v1/testing/constraints-3.11.txt | 6 + .../v1/testing/constraints-3.12.txt | 6 + .../v1/testing/constraints-3.7.txt | 9 + .../v1/testing/constraints-3.8.txt | 6 + .../v1/testing/constraints-3.9.txt | 6 + .../v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/storageinsights_v1/__init__.py | 16 + .../test_storage_insights.py | 6142 +++++++++++++++++ 58 files changed, 16122 insertions(+) create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/.flake8 create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/README.rst create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/services.rst create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/storage_insights.rst create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/types.rst create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/__init__.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/py.typed create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/py.typed create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/__init__.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/async_client.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/client.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/pagers.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/base.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/types/storageinsights.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/snippet_metadata_google.cloud.storageinsights.v1.json create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_create_report_config_async.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_create_report_config_sync.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_delete_report_config_async.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_delete_report_config_sync.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_config_async.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_config_sync.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_detail_async.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_detail_sync.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_configs_async.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_details_async.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_details_sync.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_update_report_config_async.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_update_report_config_sync.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/scripts/fixup_storageinsights_v1_keywords.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/setup.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/storageinsights_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/storageinsights_v1/test_storage_insights.py diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/.coveragerc b/owl-bot-staging/google-cloud-storageinsights/v1/.coveragerc new file mode 100644 index 000000000000..f7ef2605d609 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/storageinsights/__init__.py + google/cloud/storageinsights/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/.flake8 b/owl-bot-staging/google-cloud-storageinsights/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/MANIFEST.in b/owl-bot-staging/google-cloud-storageinsights/v1/MANIFEST.in new file mode 100644 index 000000000000..0d3cf11e4794 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/storageinsights *.py +recursive-include google/cloud/storageinsights_v1 *.py diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/README.rst b/owl-bot-staging/google-cloud-storageinsights/v1/README.rst new file mode 100644 index 000000000000..92d230819bbd --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Storageinsights API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Storageinsights API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/docs/conf.py b/owl-bot-staging/google-cloud-storageinsights/v1/docs/conf.py new file mode 100644 index 000000000000..d3fa0e29914e --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-storageinsights 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-cloud-storageinsights" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-storageinsights-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-cloud-storageinsights.tex", + u"google-cloud-storageinsights 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-cloud-storageinsights", + u"Google Cloud Storageinsights 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-cloud-storageinsights", + u"google-cloud-storageinsights Documentation", + author, + "google-cloud-storageinsights", + "GAPIC library for Google Cloud Storageinsights API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/docs/index.rst b/owl-bot-staging/google-cloud-storageinsights/v1/docs/index.rst new file mode 100644 index 000000000000..3f7f26072832 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + storageinsights_v1/services + storageinsights_v1/types diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/services.rst b/owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/services.rst new file mode 100644 index 000000000000..7e83acde00ce --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Storageinsights v1 API +================================================ +.. toctree:: + :maxdepth: 2 + + storage_insights diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/storage_insights.rst b/owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/storage_insights.rst new file mode 100644 index 000000000000..31171ab96163 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/storage_insights.rst @@ -0,0 +1,10 @@ +StorageInsights +--------------------------------- + +.. automodule:: google.cloud.storageinsights_v1.services.storage_insights + :members: + :inherited-members: + +.. automodule:: google.cloud.storageinsights_v1.services.storage_insights.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/types.rst b/owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/types.rst new file mode 100644 index 000000000000..853a2bed65f9 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Storageinsights v1 API +============================================= + +.. automodule:: google.cloud.storageinsights_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/__init__.py new file mode 100644 index 000000000000..bcf30c8d5f34 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/__init__.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.storageinsights import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.storageinsights_v1.services.storage_insights.client import StorageInsightsClient +from google.cloud.storageinsights_v1.services.storage_insights.async_client import StorageInsightsAsyncClient + +from google.cloud.storageinsights_v1.types.storageinsights import CloudStorageDestinationOptions +from google.cloud.storageinsights_v1.types.storageinsights import CloudStorageFilters +from google.cloud.storageinsights_v1.types.storageinsights import CreateReportConfigRequest +from google.cloud.storageinsights_v1.types.storageinsights import CSVOptions +from google.cloud.storageinsights_v1.types.storageinsights import DeleteReportConfigRequest +from google.cloud.storageinsights_v1.types.storageinsights import FrequencyOptions +from google.cloud.storageinsights_v1.types.storageinsights import GetReportConfigRequest +from google.cloud.storageinsights_v1.types.storageinsights import GetReportDetailRequest +from google.cloud.storageinsights_v1.types.storageinsights import ListReportConfigsRequest +from google.cloud.storageinsights_v1.types.storageinsights import ListReportConfigsResponse +from google.cloud.storageinsights_v1.types.storageinsights import ListReportDetailsRequest +from google.cloud.storageinsights_v1.types.storageinsights import ListReportDetailsResponse +from google.cloud.storageinsights_v1.types.storageinsights import ObjectMetadataReportOptions +from google.cloud.storageinsights_v1.types.storageinsights import OperationMetadata +from google.cloud.storageinsights_v1.types.storageinsights import ParquetOptions +from google.cloud.storageinsights_v1.types.storageinsights import ReportConfig +from google.cloud.storageinsights_v1.types.storageinsights import ReportDetail +from google.cloud.storageinsights_v1.types.storageinsights import UpdateReportConfigRequest + +__all__ = ('StorageInsightsClient', + 'StorageInsightsAsyncClient', + 'CloudStorageDestinationOptions', + 'CloudStorageFilters', + 'CreateReportConfigRequest', + 'CSVOptions', + 'DeleteReportConfigRequest', + 'FrequencyOptions', + 'GetReportConfigRequest', + 'GetReportDetailRequest', + 'ListReportConfigsRequest', + 'ListReportConfigsResponse', + 'ListReportDetailsRequest', + 'ListReportDetailsResponse', + 'ObjectMetadataReportOptions', + 'OperationMetadata', + 'ParquetOptions', + 'ReportConfig', + 'ReportDetail', + 'UpdateReportConfigRequest', +) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/gapic_version.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/py.typed b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/py.typed new file mode 100644 index 000000000000..83d187acf779 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-storageinsights package uses inline types. diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/__init__.py new file mode 100644 index 000000000000..2790a1860561 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/__init__.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.storageinsights_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.storage_insights import StorageInsightsClient +from .services.storage_insights import StorageInsightsAsyncClient + +from .types.storageinsights import CloudStorageDestinationOptions +from .types.storageinsights import CloudStorageFilters +from .types.storageinsights import CreateReportConfigRequest +from .types.storageinsights import CSVOptions +from .types.storageinsights import DeleteReportConfigRequest +from .types.storageinsights import FrequencyOptions +from .types.storageinsights import GetReportConfigRequest +from .types.storageinsights import GetReportDetailRequest +from .types.storageinsights import ListReportConfigsRequest +from .types.storageinsights import ListReportConfigsResponse +from .types.storageinsights import ListReportDetailsRequest +from .types.storageinsights import ListReportDetailsResponse +from .types.storageinsights import ObjectMetadataReportOptions +from .types.storageinsights import OperationMetadata +from .types.storageinsights import ParquetOptions +from .types.storageinsights import ReportConfig +from .types.storageinsights import ReportDetail +from .types.storageinsights import UpdateReportConfigRequest + +__all__ = ( + 'StorageInsightsAsyncClient', +'CSVOptions', +'CloudStorageDestinationOptions', +'CloudStorageFilters', +'CreateReportConfigRequest', +'DeleteReportConfigRequest', +'FrequencyOptions', +'GetReportConfigRequest', +'GetReportDetailRequest', +'ListReportConfigsRequest', +'ListReportConfigsResponse', +'ListReportDetailsRequest', +'ListReportDetailsResponse', +'ObjectMetadataReportOptions', +'OperationMetadata', +'ParquetOptions', +'ReportConfig', +'ReportDetail', +'StorageInsightsClient', +'UpdateReportConfigRequest', +) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/gapic_metadata.json new file mode 100644 index 000000000000..1456239dafb4 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/gapic_metadata.json @@ -0,0 +1,133 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.storageinsights_v1", + "protoPackage": "google.cloud.storageinsights.v1", + "schema": "1.0", + "services": { + "StorageInsights": { + "clients": { + "grpc": { + "libraryClient": "StorageInsightsClient", + "rpcs": { + "CreateReportConfig": { + "methods": [ + "create_report_config" + ] + }, + "DeleteReportConfig": { + "methods": [ + "delete_report_config" + ] + }, + "GetReportConfig": { + "methods": [ + "get_report_config" + ] + }, + "GetReportDetail": { + "methods": [ + "get_report_detail" + ] + }, + "ListReportConfigs": { + "methods": [ + "list_report_configs" + ] + }, + "ListReportDetails": { + "methods": [ + "list_report_details" + ] + }, + "UpdateReportConfig": { + "methods": [ + "update_report_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "StorageInsightsAsyncClient", + "rpcs": { + "CreateReportConfig": { + "methods": [ + "create_report_config" + ] + }, + "DeleteReportConfig": { + "methods": [ + "delete_report_config" + ] + }, + "GetReportConfig": { + "methods": [ + "get_report_config" + ] + }, + "GetReportDetail": { + "methods": [ + "get_report_detail" + ] + }, + "ListReportConfigs": { + "methods": [ + "list_report_configs" + ] + }, + "ListReportDetails": { + "methods": [ + "list_report_details" + ] + }, + "UpdateReportConfig": { + "methods": [ + "update_report_config" + ] + } + } + }, + "rest": { + "libraryClient": "StorageInsightsClient", + "rpcs": { + "CreateReportConfig": { + "methods": [ + "create_report_config" + ] + }, + "DeleteReportConfig": { + "methods": [ + "delete_report_config" + ] + }, + "GetReportConfig": { + "methods": [ + "get_report_config" + ] + }, + "GetReportDetail": { + "methods": [ + "get_report_detail" + ] + }, + "ListReportConfigs": { + "methods": [ + "list_report_configs" + ] + }, + "ListReportDetails": { + "methods": [ + "list_report_details" + ] + }, + "UpdateReportConfig": { + "methods": [ + "update_report_config" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/gapic_version.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/py.typed b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/py.typed new file mode 100644 index 000000000000..83d187acf779 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-storageinsights package uses inline types. diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/__init__.py new file mode 100644 index 000000000000..92168b4a07a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 StorageInsightsClient +from .async_client import StorageInsightsAsyncClient + +__all__ = ( + 'StorageInsightsClient', + 'StorageInsightsAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/async_client.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/async_client.py new file mode 100644 index 000000000000..9063010ccd29 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/async_client.py @@ -0,0 +1,1277 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.storageinsights_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.storageinsights_v1.services.storage_insights import pagers +from google.cloud.storageinsights_v1.types import storageinsights +from google.longrunning import operations_pb2 +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import datetime_pb2 # type: ignore +from .transports.base import StorageInsightsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import StorageInsightsGrpcAsyncIOTransport +from .client import StorageInsightsClient + + +class StorageInsightsAsyncClient: + """Service describing handlers for resources""" + + _client: StorageInsightsClient + + DEFAULT_ENDPOINT = StorageInsightsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = StorageInsightsClient.DEFAULT_MTLS_ENDPOINT + + report_config_path = staticmethod(StorageInsightsClient.report_config_path) + parse_report_config_path = staticmethod(StorageInsightsClient.parse_report_config_path) + report_detail_path = staticmethod(StorageInsightsClient.report_detail_path) + parse_report_detail_path = staticmethod(StorageInsightsClient.parse_report_detail_path) + common_billing_account_path = staticmethod(StorageInsightsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(StorageInsightsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(StorageInsightsClient.common_folder_path) + parse_common_folder_path = staticmethod(StorageInsightsClient.parse_common_folder_path) + common_organization_path = staticmethod(StorageInsightsClient.common_organization_path) + parse_common_organization_path = staticmethod(StorageInsightsClient.parse_common_organization_path) + common_project_path = staticmethod(StorageInsightsClient.common_project_path) + parse_common_project_path = staticmethod(StorageInsightsClient.parse_common_project_path) + common_location_path = staticmethod(StorageInsightsClient.common_location_path) + parse_common_location_path = staticmethod(StorageInsightsClient.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: + StorageInsightsAsyncClient: The constructed client. + """ + return StorageInsightsClient.from_service_account_info.__func__(StorageInsightsAsyncClient, 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: + StorageInsightsAsyncClient: The constructed client. + """ + return StorageInsightsClient.from_service_account_file.__func__(StorageInsightsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return StorageInsightsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> StorageInsightsTransport: + """Returns the transport used by the client instance. + + Returns: + StorageInsightsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(StorageInsightsClient).get_transport_class, type(StorageInsightsClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, StorageInsightsTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the storage insights 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, ~.StorageInsightsTransport]): 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 = StorageInsightsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_report_configs(self, + request: Optional[Union[storageinsights.ListReportConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListReportConfigsAsyncPager: + r"""Lists ReportConfigs in a given project and location. + + .. 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.cloud import storageinsights_v1 + + async def sample_list_report_configs(): + # Create a client + client = storageinsights_v1.StorageInsightsAsyncClient() + + # Initialize request argument(s) + request = storageinsights_v1.ListReportConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_report_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.storageinsights_v1.types.ListReportConfigsRequest, dict]]): + The request object. Message for requesting list of + ReportConfigs + parent (:class:`str`): + Required. Parent value for + ListReportConfigsRequest + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storageinsights_v1.services.storage_insights.pagers.ListReportConfigsAsyncPager: + Message for response to listing + ReportConfigs + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = storageinsights.ListReportConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_report_configs, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + 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(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListReportConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_report_config(self, + request: Optional[Union[storageinsights.GetReportConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> storageinsights.ReportConfig: + r"""Gets details of a single ReportConfig. + + .. 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.cloud import storageinsights_v1 + + async def sample_get_report_config(): + # Create a client + client = storageinsights_v1.StorageInsightsAsyncClient() + + # Initialize request argument(s) + request = storageinsights_v1.GetReportConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_report_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storageinsights_v1.types.GetReportConfigRequest, dict]]): + The request object. Message for getting a ReportConfig + name (:class:`str`): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storageinsights_v1.types.ReportConfig: + Message describing ReportConfig + object. ReportConfig is the + configuration to generate reports. See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various + fields. Next ID: 12 + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 = storageinsights.GetReportConfigRequest(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_report_config, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + 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 create_report_config(self, + request: Optional[Union[storageinsights.CreateReportConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + report_config: Optional[storageinsights.ReportConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> storageinsights.ReportConfig: + r"""Creates a new ReportConfig in a given project and + location. + + .. 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.cloud import storageinsights_v1 + + async def sample_create_report_config(): + # Create a client + client = storageinsights_v1.StorageInsightsAsyncClient() + + # Initialize request argument(s) + request = storageinsights_v1.CreateReportConfigRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_report_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storageinsights_v1.types.CreateReportConfigRequest, dict]]): + The request object. Message for creating a ReportConfig + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + report_config (:class:`google.cloud.storageinsights_v1.types.ReportConfig`): + Required. The resource being created + This corresponds to the ``report_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storageinsights_v1.types.ReportConfig: + Message describing ReportConfig + object. ReportConfig is the + configuration to generate reports. See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various + fields. Next ID: 12 + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, report_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = storageinsights.CreateReportConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if report_config is not None: + request.report_config = report_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_report_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_report_config(self, + request: Optional[Union[storageinsights.UpdateReportConfigRequest, dict]] = None, + *, + report_config: Optional[storageinsights.ReportConfig] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> storageinsights.ReportConfig: + r"""Updates the parameters of a single ReportConfig. + + .. 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.cloud import storageinsights_v1 + + async def sample_update_report_config(): + # Create a client + client = storageinsights_v1.StorageInsightsAsyncClient() + + # Initialize request argument(s) + request = storageinsights_v1.UpdateReportConfigRequest( + ) + + # Make the request + response = await client.update_report_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storageinsights_v1.types.UpdateReportConfigRequest, dict]]): + The request object. Message for updating a ReportConfig + report_config (:class:`google.cloud.storageinsights_v1.types.ReportConfig`): + Required. The resource being updated + This corresponds to the ``report_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the ReportConfig resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storageinsights_v1.types.ReportConfig: + Message describing ReportConfig + object. ReportConfig is the + configuration to generate reports. See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various + fields. Next ID: 12 + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([report_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = storageinsights.UpdateReportConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if report_config is not None: + request.report_config = report_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_report_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("report_config.name", request.report_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_report_config(self, + request: Optional[Union[storageinsights.DeleteReportConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a single ReportConfig. + + .. 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.cloud import storageinsights_v1 + + async def sample_delete_report_config(): + # Create a client + client = storageinsights_v1.StorageInsightsAsyncClient() + + # Initialize request argument(s) + request = storageinsights_v1.DeleteReportConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_report_config(request=request) + + Args: + request (Optional[Union[google.cloud.storageinsights_v1.types.DeleteReportConfigRequest, dict]]): + The request object. Message for deleting a ReportConfig + name (:class:`str`): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = storageinsights.DeleteReportConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_report_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_report_details(self, + request: Optional[Union[storageinsights.ListReportDetailsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListReportDetailsAsyncPager: + r"""Lists ReportDetails in a given project and location. + + .. 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.cloud import storageinsights_v1 + + async def sample_list_report_details(): + # Create a client + client = storageinsights_v1.StorageInsightsAsyncClient() + + # Initialize request argument(s) + request = storageinsights_v1.ListReportDetailsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_report_details(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.storageinsights_v1.types.ListReportDetailsRequest, dict]]): + The request object. Message for requesting list of + ReportDetails + parent (:class:`str`): + Required. Parent value for + ListReportDetailsRequest + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storageinsights_v1.services.storage_insights.pagers.ListReportDetailsAsyncPager: + Message for response to listing + ReportDetails + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = storageinsights.ListReportDetailsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_report_details, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + 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(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListReportDetailsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_report_detail(self, + request: Optional[Union[storageinsights.GetReportDetailRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> storageinsights.ReportDetail: + r"""Gets details of a single ReportDetail. + + .. 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.cloud import storageinsights_v1 + + async def sample_get_report_detail(): + # Create a client + client = storageinsights_v1.StorageInsightsAsyncClient() + + # Initialize request argument(s) + request = storageinsights_v1.GetReportDetailRequest( + name="name_value", + ) + + # Make the request + response = await client.get_report_detail(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storageinsights_v1.types.GetReportDetailRequest, dict]]): + The request object. Message for getting a ReportDetail + name (:class:`str`): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storageinsights_v1.types.ReportDetail: + Message describing ReportDetail + object. ReportDetail represents metadata + of generated reports for a ReportConfig. + Next ID: 10 + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 = storageinsights.GetReportDetailRequest(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_report_detail, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + 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 list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "StorageInsightsAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "StorageInsightsAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/client.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/client.py new file mode 100644 index 000000000000..d51b46ab2e31 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/client.py @@ -0,0 +1,1461 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from google.cloud.storageinsights_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.storageinsights_v1.services.storage_insights import pagers +from google.cloud.storageinsights_v1.types import storageinsights +from google.longrunning import operations_pb2 +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import datetime_pb2 # type: ignore +from .transports.base import StorageInsightsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import StorageInsightsGrpcTransport +from .transports.grpc_asyncio import StorageInsightsGrpcAsyncIOTransport +from .transports.rest import StorageInsightsRestTransport + + +class StorageInsightsClientMeta(type): + """Metaclass for the StorageInsights 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[StorageInsightsTransport]] + _transport_registry["grpc"] = StorageInsightsGrpcTransport + _transport_registry["grpc_asyncio"] = StorageInsightsGrpcAsyncIOTransport + _transport_registry["rest"] = StorageInsightsRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[StorageInsightsTransport]: + """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 StorageInsightsClient(metaclass=StorageInsightsClientMeta): + """Service describing handlers for resources""" + + @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 = "storageinsights.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: + StorageInsightsClient: 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: + StorageInsightsClient: 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) -> StorageInsightsTransport: + """Returns the transport used by the client instance. + + Returns: + StorageInsightsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def report_config_path(project: str,location: str,report_config: str,) -> str: + """Returns a fully-qualified report_config string.""" + return "projects/{project}/locations/{location}/reportConfigs/{report_config}".format(project=project, location=location, report_config=report_config, ) + + @staticmethod + def parse_report_config_path(path: str) -> Dict[str,str]: + """Parses a report_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/reportConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def report_detail_path(project: str,location: str,report_config: str,report_detail: str,) -> str: + """Returns a fully-qualified report_detail string.""" + return "projects/{project}/locations/{location}/reportConfigs/{report_config}/reportDetails/{report_detail}".format(project=project, location=location, report_config=report_config, report_detail=report_detail, ) + + @staticmethod + def parse_report_detail_path(path: str) -> Dict[str,str]: + """Parses a report_detail path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/reportConfigs/(?P.+?)/reportDetails/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + 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, StorageInsightsTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the storage insights 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, StorageInsightsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. 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, StorageInsightsTransport): + # transport is a StorageInsightsTransport 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 list_report_configs(self, + request: Optional[Union[storageinsights.ListReportConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListReportConfigsPager: + r"""Lists ReportConfigs in a given project and location. + + .. 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.cloud import storageinsights_v1 + + def sample_list_report_configs(): + # Create a client + client = storageinsights_v1.StorageInsightsClient() + + # Initialize request argument(s) + request = storageinsights_v1.ListReportConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_report_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.storageinsights_v1.types.ListReportConfigsRequest, dict]): + The request object. Message for requesting list of + ReportConfigs + parent (str): + Required. Parent value for + ListReportConfigsRequest + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storageinsights_v1.services.storage_insights.pagers.ListReportConfigsPager: + Message for response to listing + ReportConfigs + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a storageinsights.ListReportConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, storageinsights.ListReportConfigsRequest): + request = storageinsights.ListReportConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_report_configs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListReportConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_report_config(self, + request: Optional[Union[storageinsights.GetReportConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> storageinsights.ReportConfig: + r"""Gets details of a single ReportConfig. + + .. 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.cloud import storageinsights_v1 + + def sample_get_report_config(): + # Create a client + client = storageinsights_v1.StorageInsightsClient() + + # Initialize request argument(s) + request = storageinsights_v1.GetReportConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_report_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storageinsights_v1.types.GetReportConfigRequest, dict]): + The request object. Message for getting a ReportConfig + name (str): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storageinsights_v1.types.ReportConfig: + Message describing ReportConfig + object. ReportConfig is the + configuration to generate reports. See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various + fields. Next ID: 12 + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 storageinsights.GetReportConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, storageinsights.GetReportConfigRequest): + request = storageinsights.GetReportConfigRequest(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_report_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_report_config(self, + request: Optional[Union[storageinsights.CreateReportConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + report_config: Optional[storageinsights.ReportConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> storageinsights.ReportConfig: + r"""Creates a new ReportConfig in a given project and + location. + + .. 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.cloud import storageinsights_v1 + + def sample_create_report_config(): + # Create a client + client = storageinsights_v1.StorageInsightsClient() + + # Initialize request argument(s) + request = storageinsights_v1.CreateReportConfigRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_report_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storageinsights_v1.types.CreateReportConfigRequest, dict]): + The request object. Message for creating a ReportConfig + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + report_config (google.cloud.storageinsights_v1.types.ReportConfig): + Required. The resource being created + This corresponds to the ``report_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storageinsights_v1.types.ReportConfig: + Message describing ReportConfig + object. ReportConfig is the + configuration to generate reports. See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various + fields. Next ID: 12 + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, report_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a storageinsights.CreateReportConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, storageinsights.CreateReportConfigRequest): + request = storageinsights.CreateReportConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if report_config is not None: + request.report_config = report_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_report_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_report_config(self, + request: Optional[Union[storageinsights.UpdateReportConfigRequest, dict]] = None, + *, + report_config: Optional[storageinsights.ReportConfig] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> storageinsights.ReportConfig: + r"""Updates the parameters of a single ReportConfig. + + .. 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.cloud import storageinsights_v1 + + def sample_update_report_config(): + # Create a client + client = storageinsights_v1.StorageInsightsClient() + + # Initialize request argument(s) + request = storageinsights_v1.UpdateReportConfigRequest( + ) + + # Make the request + response = client.update_report_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storageinsights_v1.types.UpdateReportConfigRequest, dict]): + The request object. Message for updating a ReportConfig + report_config (google.cloud.storageinsights_v1.types.ReportConfig): + Required. The resource being updated + This corresponds to the ``report_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the ReportConfig resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storageinsights_v1.types.ReportConfig: + Message describing ReportConfig + object. ReportConfig is the + configuration to generate reports. See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various + fields. Next ID: 12 + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([report_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a storageinsights.UpdateReportConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, storageinsights.UpdateReportConfigRequest): + request = storageinsights.UpdateReportConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if report_config is not None: + request.report_config = report_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_report_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("report_config.name", request.report_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_report_config(self, + request: Optional[Union[storageinsights.DeleteReportConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a single ReportConfig. + + .. 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.cloud import storageinsights_v1 + + def sample_delete_report_config(): + # Create a client + client = storageinsights_v1.StorageInsightsClient() + + # Initialize request argument(s) + request = storageinsights_v1.DeleteReportConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_report_config(request=request) + + Args: + request (Union[google.cloud.storageinsights_v1.types.DeleteReportConfigRequest, dict]): + The request object. Message for deleting a ReportConfig + name (str): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a storageinsights.DeleteReportConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, storageinsights.DeleteReportConfigRequest): + request = storageinsights.DeleteReportConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_report_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_report_details(self, + request: Optional[Union[storageinsights.ListReportDetailsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListReportDetailsPager: + r"""Lists ReportDetails in a given project and location. + + .. 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.cloud import storageinsights_v1 + + def sample_list_report_details(): + # Create a client + client = storageinsights_v1.StorageInsightsClient() + + # Initialize request argument(s) + request = storageinsights_v1.ListReportDetailsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_report_details(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.storageinsights_v1.types.ListReportDetailsRequest, dict]): + The request object. Message for requesting list of + ReportDetails + parent (str): + Required. Parent value for + ListReportDetailsRequest + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storageinsights_v1.services.storage_insights.pagers.ListReportDetailsPager: + Message for response to listing + ReportDetails + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a storageinsights.ListReportDetailsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, storageinsights.ListReportDetailsRequest): + request = storageinsights.ListReportDetailsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_report_details] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListReportDetailsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_report_detail(self, + request: Optional[Union[storageinsights.GetReportDetailRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> storageinsights.ReportDetail: + r"""Gets details of a single ReportDetail. + + .. 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.cloud import storageinsights_v1 + + def sample_get_report_detail(): + # Create a client + client = storageinsights_v1.StorageInsightsClient() + + # Initialize request argument(s) + request = storageinsights_v1.GetReportDetailRequest( + name="name_value", + ) + + # Make the request + response = client.get_report_detail(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storageinsights_v1.types.GetReportDetailRequest, dict]): + The request object. Message for getting a ReportDetail + name (str): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storageinsights_v1.types.ReportDetail: + Message describing ReportDetail + object. ReportDetail represents metadata + of generated reports for a ReportConfig. + Next ID: 10 + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 storageinsights.GetReportDetailRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, storageinsights.GetReportDetailRequest): + request = storageinsights.GetReportDetailRequest(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_report_detail] + + # Certain 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 __enter__(self) -> "StorageInsightsClient": + 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() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "StorageInsightsClient", +) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/pagers.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/pagers.py new file mode 100644 index 000000000000..8b990938faa0 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/pagers.py @@ -0,0 +1,260 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.storageinsights_v1.types import storageinsights + + +class ListReportConfigsPager: + """A pager for iterating through ``list_report_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storageinsights_v1.types.ListReportConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``report_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListReportConfigs`` requests and continue to iterate + through the ``report_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storageinsights_v1.types.ListReportConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., storageinsights.ListReportConfigsResponse], + request: storageinsights.ListReportConfigsRequest, + response: storageinsights.ListReportConfigsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.storageinsights_v1.types.ListReportConfigsRequest): + The initial request object. + response (google.cloud.storageinsights_v1.types.ListReportConfigsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = storageinsights.ListReportConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[storageinsights.ListReportConfigsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[storageinsights.ReportConfig]: + for page in self.pages: + yield from page.report_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListReportConfigsAsyncPager: + """A pager for iterating through ``list_report_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storageinsights_v1.types.ListReportConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``report_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListReportConfigs`` requests and continue to iterate + through the ``report_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storageinsights_v1.types.ListReportConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[storageinsights.ListReportConfigsResponse]], + request: storageinsights.ListReportConfigsRequest, + response: storageinsights.ListReportConfigsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.storageinsights_v1.types.ListReportConfigsRequest): + The initial request object. + response (google.cloud.storageinsights_v1.types.ListReportConfigsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = storageinsights.ListReportConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[storageinsights.ListReportConfigsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[storageinsights.ReportConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.report_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListReportDetailsPager: + """A pager for iterating through ``list_report_details`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storageinsights_v1.types.ListReportDetailsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``report_details`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListReportDetails`` requests and continue to iterate + through the ``report_details`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storageinsights_v1.types.ListReportDetailsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., storageinsights.ListReportDetailsResponse], + request: storageinsights.ListReportDetailsRequest, + response: storageinsights.ListReportDetailsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.storageinsights_v1.types.ListReportDetailsRequest): + The initial request object. + response (google.cloud.storageinsights_v1.types.ListReportDetailsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = storageinsights.ListReportDetailsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[storageinsights.ListReportDetailsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[storageinsights.ReportDetail]: + for page in self.pages: + yield from page.report_details + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListReportDetailsAsyncPager: + """A pager for iterating through ``list_report_details`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storageinsights_v1.types.ListReportDetailsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``report_details`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListReportDetails`` requests and continue to iterate + through the ``report_details`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storageinsights_v1.types.ListReportDetailsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[storageinsights.ListReportDetailsResponse]], + request: storageinsights.ListReportDetailsRequest, + response: storageinsights.ListReportDetailsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.storageinsights_v1.types.ListReportDetailsRequest): + The initial request object. + response (google.cloud.storageinsights_v1.types.ListReportDetailsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = storageinsights.ListReportDetailsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[storageinsights.ListReportDetailsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[storageinsights.ReportDetail]: + async def async_generator(): + async for page in self.pages: + for response in page.report_details: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/__init__.py new file mode 100644 index 000000000000..582c4e3c6534 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 StorageInsightsTransport +from .grpc import StorageInsightsGrpcTransport +from .grpc_asyncio import StorageInsightsGrpcAsyncIOTransport +from .rest import StorageInsightsRestTransport +from .rest import StorageInsightsRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[StorageInsightsTransport]] +_transport_registry['grpc'] = StorageInsightsGrpcTransport +_transport_registry['grpc_asyncio'] = StorageInsightsGrpcAsyncIOTransport +_transport_registry['rest'] = StorageInsightsRestTransport + +__all__ = ( + 'StorageInsightsTransport', + 'StorageInsightsGrpcTransport', + 'StorageInsightsGrpcAsyncIOTransport', + 'StorageInsightsRestTransport', + 'StorageInsightsRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/base.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/base.py new file mode 100644 index 000000000000..0abd0f1aa732 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/base.py @@ -0,0 +1,311 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.storageinsights_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.storageinsights_v1.types import storageinsights +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class StorageInsightsTransport(abc.ABC): + """Abstract transport class for StorageInsights.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'storageinsights.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.list_report_configs: gapic_v1.method.wrap_method( + self.list_report_configs, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_report_config: gapic_v1.method.wrap_method( + self.get_report_config, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_report_config: gapic_v1.method.wrap_method( + self.create_report_config, + default_timeout=None, + client_info=client_info, + ), + self.update_report_config: gapic_v1.method.wrap_method( + self.update_report_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_report_config: gapic_v1.method.wrap_method( + self.delete_report_config, + default_timeout=None, + client_info=client_info, + ), + self.list_report_details: gapic_v1.method.wrap_method( + self.list_report_details, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_report_detail: gapic_v1.method.wrap_method( + self.get_report_detail, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + 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 list_report_configs(self) -> Callable[ + [storageinsights.ListReportConfigsRequest], + Union[ + storageinsights.ListReportConfigsResponse, + Awaitable[storageinsights.ListReportConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def get_report_config(self) -> Callable[ + [storageinsights.GetReportConfigRequest], + Union[ + storageinsights.ReportConfig, + Awaitable[storageinsights.ReportConfig] + ]]: + raise NotImplementedError() + + @property + def create_report_config(self) -> Callable[ + [storageinsights.CreateReportConfigRequest], + Union[ + storageinsights.ReportConfig, + Awaitable[storageinsights.ReportConfig] + ]]: + raise NotImplementedError() + + @property + def update_report_config(self) -> Callable[ + [storageinsights.UpdateReportConfigRequest], + Union[ + storageinsights.ReportConfig, + Awaitable[storageinsights.ReportConfig] + ]]: + raise NotImplementedError() + + @property + def delete_report_config(self) -> Callable[ + [storageinsights.DeleteReportConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_report_details(self) -> Callable[ + [storageinsights.ListReportDetailsRequest], + Union[ + storageinsights.ListReportDetailsResponse, + Awaitable[storageinsights.ListReportDetailsResponse] + ]]: + raise NotImplementedError() + + @property + def get_report_detail(self) -> Callable[ + [storageinsights.GetReportDetailRequest], + Union[ + storageinsights.ReportDetail, + Awaitable[storageinsights.ReportDetail] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'StorageInsightsTransport', +) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/grpc.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/grpc.py new file mode 100644 index 000000000000..1007801a31d8 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/grpc.py @@ -0,0 +1,532 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.storageinsights_v1.types import storageinsights +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from .base import StorageInsightsTransport, DEFAULT_CLIENT_INFO + + +class StorageInsightsGrpcTransport(StorageInsightsTransport): + """gRPC backend transport for StorageInsights. + + Service describing handlers for resources + + 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 = 'storageinsights.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 = 'storageinsights.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 list_report_configs(self) -> Callable[ + [storageinsights.ListReportConfigsRequest], + storageinsights.ListReportConfigsResponse]: + r"""Return a callable for the list report configs method over gRPC. + + Lists ReportConfigs in a given project and location. + + Returns: + Callable[[~.ListReportConfigsRequest], + ~.ListReportConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_report_configs' not in self._stubs: + self._stubs['list_report_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.storageinsights.v1.StorageInsights/ListReportConfigs', + request_serializer=storageinsights.ListReportConfigsRequest.serialize, + response_deserializer=storageinsights.ListReportConfigsResponse.deserialize, + ) + return self._stubs['list_report_configs'] + + @property + def get_report_config(self) -> Callable[ + [storageinsights.GetReportConfigRequest], + storageinsights.ReportConfig]: + r"""Return a callable for the get report config method over gRPC. + + Gets details of a single ReportConfig. + + Returns: + Callable[[~.GetReportConfigRequest], + ~.ReportConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_report_config' not in self._stubs: + self._stubs['get_report_config'] = self.grpc_channel.unary_unary( + '/google.cloud.storageinsights.v1.StorageInsights/GetReportConfig', + request_serializer=storageinsights.GetReportConfigRequest.serialize, + response_deserializer=storageinsights.ReportConfig.deserialize, + ) + return self._stubs['get_report_config'] + + @property + def create_report_config(self) -> Callable[ + [storageinsights.CreateReportConfigRequest], + storageinsights.ReportConfig]: + r"""Return a callable for the create report config method over gRPC. + + Creates a new ReportConfig in a given project and + location. + + Returns: + Callable[[~.CreateReportConfigRequest], + ~.ReportConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_report_config' not in self._stubs: + self._stubs['create_report_config'] = self.grpc_channel.unary_unary( + '/google.cloud.storageinsights.v1.StorageInsights/CreateReportConfig', + request_serializer=storageinsights.CreateReportConfigRequest.serialize, + response_deserializer=storageinsights.ReportConfig.deserialize, + ) + return self._stubs['create_report_config'] + + @property + def update_report_config(self) -> Callable[ + [storageinsights.UpdateReportConfigRequest], + storageinsights.ReportConfig]: + r"""Return a callable for the update report config method over gRPC. + + Updates the parameters of a single ReportConfig. + + Returns: + Callable[[~.UpdateReportConfigRequest], + ~.ReportConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_report_config' not in self._stubs: + self._stubs['update_report_config'] = self.grpc_channel.unary_unary( + '/google.cloud.storageinsights.v1.StorageInsights/UpdateReportConfig', + request_serializer=storageinsights.UpdateReportConfigRequest.serialize, + response_deserializer=storageinsights.ReportConfig.deserialize, + ) + return self._stubs['update_report_config'] + + @property + def delete_report_config(self) -> Callable[ + [storageinsights.DeleteReportConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete report config method over gRPC. + + Deletes a single ReportConfig. + + Returns: + Callable[[~.DeleteReportConfigRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_report_config' not in self._stubs: + self._stubs['delete_report_config'] = self.grpc_channel.unary_unary( + '/google.cloud.storageinsights.v1.StorageInsights/DeleteReportConfig', + request_serializer=storageinsights.DeleteReportConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_report_config'] + + @property + def list_report_details(self) -> Callable[ + [storageinsights.ListReportDetailsRequest], + storageinsights.ListReportDetailsResponse]: + r"""Return a callable for the list report details method over gRPC. + + Lists ReportDetails in a given project and location. + + Returns: + Callable[[~.ListReportDetailsRequest], + ~.ListReportDetailsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_report_details' not in self._stubs: + self._stubs['list_report_details'] = self.grpc_channel.unary_unary( + '/google.cloud.storageinsights.v1.StorageInsights/ListReportDetails', + request_serializer=storageinsights.ListReportDetailsRequest.serialize, + response_deserializer=storageinsights.ListReportDetailsResponse.deserialize, + ) + return self._stubs['list_report_details'] + + @property + def get_report_detail(self) -> Callable[ + [storageinsights.GetReportDetailRequest], + storageinsights.ReportDetail]: + r"""Return a callable for the get report detail method over gRPC. + + Gets details of a single ReportDetail. + + Returns: + Callable[[~.GetReportDetailRequest], + ~.ReportDetail]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_report_detail' not in self._stubs: + self._stubs['get_report_detail'] = self.grpc_channel.unary_unary( + '/google.cloud.storageinsights.v1.StorageInsights/GetReportDetail', + request_serializer=storageinsights.GetReportDetailRequest.serialize, + response_deserializer=storageinsights.ReportDetail.deserialize, + ) + return self._stubs['get_report_detail'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-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_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-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_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'StorageInsightsGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/grpc_asyncio.py new file mode 100644 index 000000000000..8a8ecfa59d3f --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/grpc_asyncio.py @@ -0,0 +1,531 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.storageinsights_v1.types import storageinsights +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from .base import StorageInsightsTransport, DEFAULT_CLIENT_INFO +from .grpc import StorageInsightsGrpcTransport + + +class StorageInsightsGrpcAsyncIOTransport(StorageInsightsTransport): + """gRPC AsyncIO backend transport for StorageInsights. + + Service describing handlers for resources + + 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 = 'storageinsights.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 = 'storageinsights.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 list_report_configs(self) -> Callable[ + [storageinsights.ListReportConfigsRequest], + Awaitable[storageinsights.ListReportConfigsResponse]]: + r"""Return a callable for the list report configs method over gRPC. + + Lists ReportConfigs in a given project and location. + + Returns: + Callable[[~.ListReportConfigsRequest], + Awaitable[~.ListReportConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_report_configs' not in self._stubs: + self._stubs['list_report_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.storageinsights.v1.StorageInsights/ListReportConfigs', + request_serializer=storageinsights.ListReportConfigsRequest.serialize, + response_deserializer=storageinsights.ListReportConfigsResponse.deserialize, + ) + return self._stubs['list_report_configs'] + + @property + def get_report_config(self) -> Callable[ + [storageinsights.GetReportConfigRequest], + Awaitable[storageinsights.ReportConfig]]: + r"""Return a callable for the get report config method over gRPC. + + Gets details of a single ReportConfig. + + Returns: + Callable[[~.GetReportConfigRequest], + Awaitable[~.ReportConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_report_config' not in self._stubs: + self._stubs['get_report_config'] = self.grpc_channel.unary_unary( + '/google.cloud.storageinsights.v1.StorageInsights/GetReportConfig', + request_serializer=storageinsights.GetReportConfigRequest.serialize, + response_deserializer=storageinsights.ReportConfig.deserialize, + ) + return self._stubs['get_report_config'] + + @property + def create_report_config(self) -> Callable[ + [storageinsights.CreateReportConfigRequest], + Awaitable[storageinsights.ReportConfig]]: + r"""Return a callable for the create report config method over gRPC. + + Creates a new ReportConfig in a given project and + location. + + Returns: + Callable[[~.CreateReportConfigRequest], + Awaitable[~.ReportConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_report_config' not in self._stubs: + self._stubs['create_report_config'] = self.grpc_channel.unary_unary( + '/google.cloud.storageinsights.v1.StorageInsights/CreateReportConfig', + request_serializer=storageinsights.CreateReportConfigRequest.serialize, + response_deserializer=storageinsights.ReportConfig.deserialize, + ) + return self._stubs['create_report_config'] + + @property + def update_report_config(self) -> Callable[ + [storageinsights.UpdateReportConfigRequest], + Awaitable[storageinsights.ReportConfig]]: + r"""Return a callable for the update report config method over gRPC. + + Updates the parameters of a single ReportConfig. + + Returns: + Callable[[~.UpdateReportConfigRequest], + Awaitable[~.ReportConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_report_config' not in self._stubs: + self._stubs['update_report_config'] = self.grpc_channel.unary_unary( + '/google.cloud.storageinsights.v1.StorageInsights/UpdateReportConfig', + request_serializer=storageinsights.UpdateReportConfigRequest.serialize, + response_deserializer=storageinsights.ReportConfig.deserialize, + ) + return self._stubs['update_report_config'] + + @property + def delete_report_config(self) -> Callable[ + [storageinsights.DeleteReportConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete report config method over gRPC. + + Deletes a single ReportConfig. + + Returns: + Callable[[~.DeleteReportConfigRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_report_config' not in self._stubs: + self._stubs['delete_report_config'] = self.grpc_channel.unary_unary( + '/google.cloud.storageinsights.v1.StorageInsights/DeleteReportConfig', + request_serializer=storageinsights.DeleteReportConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_report_config'] + + @property + def list_report_details(self) -> Callable[ + [storageinsights.ListReportDetailsRequest], + Awaitable[storageinsights.ListReportDetailsResponse]]: + r"""Return a callable for the list report details method over gRPC. + + Lists ReportDetails in a given project and location. + + Returns: + Callable[[~.ListReportDetailsRequest], + Awaitable[~.ListReportDetailsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_report_details' not in self._stubs: + self._stubs['list_report_details'] = self.grpc_channel.unary_unary( + '/google.cloud.storageinsights.v1.StorageInsights/ListReportDetails', + request_serializer=storageinsights.ListReportDetailsRequest.serialize, + response_deserializer=storageinsights.ListReportDetailsResponse.deserialize, + ) + return self._stubs['list_report_details'] + + @property + def get_report_detail(self) -> Callable[ + [storageinsights.GetReportDetailRequest], + Awaitable[storageinsights.ReportDetail]]: + r"""Return a callable for the get report detail method over gRPC. + + Gets details of a single ReportDetail. + + Returns: + Callable[[~.GetReportDetailRequest], + Awaitable[~.ReportDetail]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_report_detail' not in self._stubs: + self._stubs['get_report_detail'] = self.grpc_channel.unary_unary( + '/google.cloud.storageinsights.v1.StorageInsights/GetReportDetail', + request_serializer=storageinsights.GetReportDetailRequest.serialize, + response_deserializer=storageinsights.ReportDetail.deserialize, + ) + return self._stubs['get_report_detail'] + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-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_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-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_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ( + 'StorageInsightsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/rest.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/rest.py new file mode 100644 index 000000000000..f28464cddab7 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/rest.py @@ -0,0 +1,1475 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.storageinsights_v1.types import storageinsights +from google.protobuf import empty_pb2 # type: ignore + +from .base import StorageInsightsTransport, 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 StorageInsightsRestInterceptor: + """Interceptor for StorageInsights. + + 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 StorageInsightsRestTransport. + + .. code-block:: python + class MyCustomStorageInsightsInterceptor(StorageInsightsRestInterceptor): + def pre_create_report_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_report_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_report_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_report_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_report_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_report_detail(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_report_detail(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_report_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_report_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_report_details(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_report_details(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_report_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_report_config(self, response): + logging.log(f"Received response: {response}") + return response + + transport = StorageInsightsRestTransport(interceptor=MyCustomStorageInsightsInterceptor()) + client = StorageInsightsClient(transport=transport) + + + """ + def pre_create_report_config(self, request: storageinsights.CreateReportConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[storageinsights.CreateReportConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_report_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageInsights server. + """ + return request, metadata + + def post_create_report_config(self, response: storageinsights.ReportConfig) -> storageinsights.ReportConfig: + """Post-rpc interceptor for create_report_config + + Override in a subclass to manipulate the response + after it is returned by the StorageInsights server but before + it is returned to user code. + """ + return response + def pre_delete_report_config(self, request: storageinsights.DeleteReportConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[storageinsights.DeleteReportConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_report_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageInsights server. + """ + return request, metadata + + def pre_get_report_config(self, request: storageinsights.GetReportConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[storageinsights.GetReportConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_report_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageInsights server. + """ + return request, metadata + + def post_get_report_config(self, response: storageinsights.ReportConfig) -> storageinsights.ReportConfig: + """Post-rpc interceptor for get_report_config + + Override in a subclass to manipulate the response + after it is returned by the StorageInsights server but before + it is returned to user code. + """ + return response + def pre_get_report_detail(self, request: storageinsights.GetReportDetailRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[storageinsights.GetReportDetailRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_report_detail + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageInsights server. + """ + return request, metadata + + def post_get_report_detail(self, response: storageinsights.ReportDetail) -> storageinsights.ReportDetail: + """Post-rpc interceptor for get_report_detail + + Override in a subclass to manipulate the response + after it is returned by the StorageInsights server but before + it is returned to user code. + """ + return response + def pre_list_report_configs(self, request: storageinsights.ListReportConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[storageinsights.ListReportConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_report_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageInsights server. + """ + return request, metadata + + def post_list_report_configs(self, response: storageinsights.ListReportConfigsResponse) -> storageinsights.ListReportConfigsResponse: + """Post-rpc interceptor for list_report_configs + + Override in a subclass to manipulate the response + after it is returned by the StorageInsights server but before + it is returned to user code. + """ + return response + def pre_list_report_details(self, request: storageinsights.ListReportDetailsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[storageinsights.ListReportDetailsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_report_details + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageInsights server. + """ + return request, metadata + + def post_list_report_details(self, response: storageinsights.ListReportDetailsResponse) -> storageinsights.ListReportDetailsResponse: + """Post-rpc interceptor for list_report_details + + Override in a subclass to manipulate the response + after it is returned by the StorageInsights server but before + it is returned to user code. + """ + return response + def pre_update_report_config(self, request: storageinsights.UpdateReportConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[storageinsights.UpdateReportConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_report_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageInsights server. + """ + return request, metadata + + def post_update_report_config(self, response: storageinsights.ReportConfig) -> storageinsights.ReportConfig: + """Post-rpc interceptor for update_report_config + + Override in a subclass to manipulate the response + after it is returned by the StorageInsights server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageInsights server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the StorageInsights server but before + it is returned to user code. + """ + return response + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageInsights server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the StorageInsights server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageInsights server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the StorageInsights server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageInsights server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the StorageInsights server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageInsights server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the StorageInsights server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageInsights server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the StorageInsights server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class StorageInsightsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: StorageInsightsRestInterceptor + + +class StorageInsightsRestTransport(StorageInsightsTransport): + """REST backend transport for StorageInsights. + + Service describing handlers for resources + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'storageinsights.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[StorageInsightsRestInterceptor] = None, + 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. + + 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 StorageInsightsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateReportConfig(StorageInsightsRestStub): + def __hash__(self): + return hash("CreateReportConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: storageinsights.CreateReportConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> storageinsights.ReportConfig: + r"""Call the create report config method over HTTP. + + Args: + request (~.storageinsights.CreateReportConfigRequest): + The request object. Message for creating a ReportConfig + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.storageinsights.ReportConfig: + Message describing ReportConfig + object. ReportConfig is the + configuration to generate reports. See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various + fields. Next ID: 12 + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/reportConfigs', + 'body': 'report_config', + }, + ] + request, metadata = self._interceptor.pre_create_report_config(request, metadata) + pb_request = storageinsights.CreateReportConfigRequest.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=True + ) + 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=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = storageinsights.ReportConfig() + pb_resp = storageinsights.ReportConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_report_config(resp) + return resp + + class _DeleteReportConfig(StorageInsightsRestStub): + def __hash__(self): + return hash("DeleteReportConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: storageinsights.DeleteReportConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete report config method over HTTP. + + Args: + request (~.storageinsights.DeleteReportConfigRequest): + The request object. Message for deleting a ReportConfig + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/reportConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_report_config(request, metadata) + pb_request = storageinsights.DeleteReportConfigRequest.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=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetReportConfig(StorageInsightsRestStub): + def __hash__(self): + return hash("GetReportConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: storageinsights.GetReportConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> storageinsights.ReportConfig: + r"""Call the get report config method over HTTP. + + Args: + request (~.storageinsights.GetReportConfigRequest): + The request object. Message for getting a ReportConfig + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.storageinsights.ReportConfig: + Message describing ReportConfig + object. ReportConfig is the + configuration to generate reports. See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various + fields. Next ID: 12 + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/reportConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_report_config(request, metadata) + pb_request = storageinsights.GetReportConfigRequest.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=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = storageinsights.ReportConfig() + pb_resp = storageinsights.ReportConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_report_config(resp) + return resp + + class _GetReportDetail(StorageInsightsRestStub): + def __hash__(self): + return hash("GetReportDetail") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: storageinsights.GetReportDetailRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> storageinsights.ReportDetail: + r"""Call the get report detail method over HTTP. + + Args: + request (~.storageinsights.GetReportDetailRequest): + The request object. Message for getting a ReportDetail + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.storageinsights.ReportDetail: + Message describing ReportDetail + object. ReportDetail represents metadata + of generated reports for a ReportConfig. + Next ID: 10 + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/reportConfigs/*/reportDetails/*}', + }, + ] + request, metadata = self._interceptor.pre_get_report_detail(request, metadata) + pb_request = storageinsights.GetReportDetailRequest.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=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = storageinsights.ReportDetail() + pb_resp = storageinsights.ReportDetail.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_report_detail(resp) + return resp + + class _ListReportConfigs(StorageInsightsRestStub): + def __hash__(self): + return hash("ListReportConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: storageinsights.ListReportConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> storageinsights.ListReportConfigsResponse: + r"""Call the list report configs method over HTTP. + + Args: + request (~.storageinsights.ListReportConfigsRequest): + The request object. Message for requesting list of + ReportConfigs + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.storageinsights.ListReportConfigsResponse: + Message for response to listing + ReportConfigs + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/reportConfigs', + }, + ] + request, metadata = self._interceptor.pre_list_report_configs(request, metadata) + pb_request = storageinsights.ListReportConfigsRequest.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=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = storageinsights.ListReportConfigsResponse() + pb_resp = storageinsights.ListReportConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_report_configs(resp) + return resp + + class _ListReportDetails(StorageInsightsRestStub): + def __hash__(self): + return hash("ListReportDetails") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: storageinsights.ListReportDetailsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> storageinsights.ListReportDetailsResponse: + r"""Call the list report details method over HTTP. + + Args: + request (~.storageinsights.ListReportDetailsRequest): + The request object. Message for requesting list of + ReportDetails + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.storageinsights.ListReportDetailsResponse: + Message for response to listing + ReportDetails + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/reportConfigs/*}/reportDetails', + }, + ] + request, metadata = self._interceptor.pre_list_report_details(request, metadata) + pb_request = storageinsights.ListReportDetailsRequest.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=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = storageinsights.ListReportDetailsResponse() + pb_resp = storageinsights.ListReportDetailsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_report_details(resp) + return resp + + class _UpdateReportConfig(StorageInsightsRestStub): + def __hash__(self): + return hash("UpdateReportConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: storageinsights.UpdateReportConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> storageinsights.ReportConfig: + r"""Call the update report config method over HTTP. + + Args: + request (~.storageinsights.UpdateReportConfigRequest): + The request object. Message for updating a ReportConfig + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.storageinsights.ReportConfig: + Message describing ReportConfig + object. ReportConfig is the + configuration to generate reports. See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various + fields. Next ID: 12 + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{report_config.name=projects/*/locations/*/reportConfigs/*}', + 'body': 'report_config', + }, + ] + request, metadata = self._interceptor.pre_update_report_config(request, metadata) + pb_request = storageinsights.UpdateReportConfigRequest.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=True + ) + 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=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = storageinsights.ReportConfig() + pb_resp = storageinsights.ReportConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_report_config(resp) + return resp + + @property + def create_report_config(self) -> Callable[ + [storageinsights.CreateReportConfigRequest], + storageinsights.ReportConfig]: + # 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._CreateReportConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_report_config(self) -> Callable[ + [storageinsights.DeleteReportConfigRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteReportConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_report_config(self) -> Callable[ + [storageinsights.GetReportConfigRequest], + storageinsights.ReportConfig]: + # 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._GetReportConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_report_detail(self) -> Callable[ + [storageinsights.GetReportDetailRequest], + storageinsights.ReportDetail]: + # 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._GetReportDetail(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_report_configs(self) -> Callable[ + [storageinsights.ListReportConfigsRequest], + storageinsights.ListReportConfigsResponse]: + # 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._ListReportConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_report_details(self) -> Callable[ + [storageinsights.ListReportDetailsRequest], + storageinsights.ListReportDetailsResponse]: + # 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._ListReportDetails(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_report_config(self) -> Callable[ + [storageinsights.UpdateReportConfigRequest], + storageinsights.ReportConfig]: + # 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._UpdateReportConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(StorageInsightsRestStub): + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['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), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(StorageInsightsRestStub): + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/locations', + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['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), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(StorageInsightsRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['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), + 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 self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(StorageInsightsRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['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), + ) + + # 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 self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(StorageInsightsRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['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), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(StorageInsightsRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['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), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'StorageInsightsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/types/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/types/__init__.py new file mode 100644 index 000000000000..4c456bf92ed7 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/types/__init__.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .storageinsights import ( + CloudStorageDestinationOptions, + CloudStorageFilters, + CreateReportConfigRequest, + CSVOptions, + DeleteReportConfigRequest, + FrequencyOptions, + GetReportConfigRequest, + GetReportDetailRequest, + ListReportConfigsRequest, + ListReportConfigsResponse, + ListReportDetailsRequest, + ListReportDetailsResponse, + ObjectMetadataReportOptions, + OperationMetadata, + ParquetOptions, + ReportConfig, + ReportDetail, + UpdateReportConfigRequest, +) + +__all__ = ( + 'CloudStorageDestinationOptions', + 'CloudStorageFilters', + 'CreateReportConfigRequest', + 'CSVOptions', + 'DeleteReportConfigRequest', + 'FrequencyOptions', + 'GetReportConfigRequest', + 'GetReportDetailRequest', + 'ListReportConfigsRequest', + 'ListReportConfigsResponse', + 'ListReportDetailsRequest', + 'ListReportDetailsResponse', + 'ObjectMetadataReportOptions', + 'OperationMetadata', + 'ParquetOptions', + 'ReportConfig', + 'ReportDetail', + 'UpdateReportConfigRequest', +) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/types/storageinsights.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/types/storageinsights.py new file mode 100644 index 000000000000..b26adf510320 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/types/storageinsights.py @@ -0,0 +1,764 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +from google.type import datetime_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.storageinsights.v1', + manifest={ + 'ListReportConfigsRequest', + 'ListReportConfigsResponse', + 'GetReportConfigRequest', + 'CreateReportConfigRequest', + 'UpdateReportConfigRequest', + 'DeleteReportConfigRequest', + 'ReportDetail', + 'ListReportDetailsRequest', + 'ListReportDetailsResponse', + 'GetReportDetailRequest', + 'OperationMetadata', + 'FrequencyOptions', + 'CSVOptions', + 'ParquetOptions', + 'CloudStorageFilters', + 'CloudStorageDestinationOptions', + 'ObjectMetadataReportOptions', + 'ReportConfig', + }, +) + + +class ListReportConfigsRequest(proto.Message): + r"""Message for requesting list of ReportConfigs + + Attributes: + parent (str): + Required. Parent value for + ListReportConfigsRequest + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results + order_by (str): + Hint for how to order the results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListReportConfigsResponse(proto.Message): + r"""Message for response to listing ReportConfigs + + Attributes: + report_configs (MutableSequence[google.cloud.storageinsights_v1.types.ReportConfig]): + The list of ReportConfig + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + report_configs: MutableSequence['ReportConfig'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ReportConfig', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetReportConfigRequest(proto.Message): + r"""Message for getting a ReportConfig + + Attributes: + name (str): + Required. Name of the resource + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateReportConfigRequest(proto.Message): + r"""Message for creating a ReportConfig + + Attributes: + parent (str): + Required. Value for parent. + report_config (google.cloud.storageinsights_v1.types.ReportConfig): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + report_config: 'ReportConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='ReportConfig', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateReportConfigRequest(proto.Message): + r"""Message for updating a ReportConfig + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the ReportConfig resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + report_config (google.cloud.storageinsights_v1.types.ReportConfig): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + report_config: 'ReportConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='ReportConfig', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteReportConfigRequest(proto.Message): + r"""Message for deleting a ReportConfig + + Attributes: + name (str): + Required. Name of the resource + force (bool): + Optional. If set, all ReportDetails for this + ReportConfig will be deleted. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ReportDetail(proto.Message): + r"""Message describing ReportDetail object. ReportDetail + represents metadata of generated reports for a ReportConfig. + Next ID: 10 + + Attributes: + name (str): + Name of resource. It will be of form + projects//locations//reportConfigs//reportDetails/. + snapshot_time (google.protobuf.timestamp_pb2.Timestamp): + The snapshot time. + All the report data is referenced at this point + of time. + report_path_prefix (str): + Prefix of the object name of each report's shard. This will + have full prefix except the "extension" and "shard_id". For + example, if the ``destination_path`` is + ``{{report-config-id}}/dt={{datetime}}``, the shard object + name would be + ``gs://my-insights/1A34-F2E456-12B456-1C3D/dt=2022-05-20T06:35/1A34-F2E456-12B456-1C3D_2022-05-20T06:35_5.csv`` + and the value of ``report_path_prefix`` field would be + ``gs://my-insights/1A34-F2E456-12B456-1C3D/dt=2022-05-20T06:35/1A34-F2E456-12B456-1C3D_2022-05-20T06:35_``. + shards_count (int): + Total shards generated for the report. + status (google.rpc.status_pb2.Status): + Status of the ReportDetail. + labels (MutableMapping[str, str]): + Labels as key value pairs + target_datetime (google.type.datetime_pb2.DateTime): + The date for which report is generated. The time part of + target_datetime will be zero till we support multiple + reports per day. + report_metrics (google.cloud.storageinsights_v1.types.ReportDetail.Metrics): + Metrics of the report. + """ + + class Metrics(proto.Message): + r"""Different metrics associated with the generated report. + + Attributes: + processed_records_count (int): + Count of Cloud Storage objects which are part + of the report. + """ + + processed_records_count: int = proto.Field( + proto.INT64, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + snapshot_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + report_path_prefix: str = proto.Field( + proto.STRING, + number=8, + ) + shards_count: int = proto.Field( + proto.INT64, + number=9, + ) + status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=4, + message=status_pb2.Status, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + target_datetime: datetime_pb2.DateTime = proto.Field( + proto.MESSAGE, + number=6, + message=datetime_pb2.DateTime, + ) + report_metrics: Metrics = proto.Field( + proto.MESSAGE, + number=7, + message=Metrics, + ) + + +class ListReportDetailsRequest(proto.Message): + r"""Message for requesting list of ReportDetails + + Attributes: + parent (str): + Required. Parent value for + ListReportDetailsRequest + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results + order_by (str): + Hint for how to order the results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListReportDetailsResponse(proto.Message): + r"""Message for response to listing ReportDetails + + Attributes: + report_details (MutableSequence[google.cloud.storageinsights_v1.types.ReportDetail]): + The list of ReportDetail + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + report_details: MutableSequence['ReportDetail'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ReportDetail', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetReportDetailRequest(proto.Message): + r"""Message for getting a ReportDetail + + Attributes: + name (str): + Required. Name of the resource + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have been + cancelled successfully have [Operation.error][] value with a + [google.rpc.Status.code][google.rpc.Status.code] of 1, + corresponding to ``Code.CANCELLED``. + api_version (str): + Output only. API version used to start the + operation. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +class FrequencyOptions(proto.Message): + r"""ReportConfig Resource: + + Options to setup frequency of report generation. + + Attributes: + frequency (google.cloud.storageinsights_v1.types.FrequencyOptions.Frequency): + Frequency of report generation. + start_date (google.type.date_pb2.Date): + The date from which report generation should + start. UTC time zone. + end_date (google.type.date_pb2.Date): + The date on which report generation should + stop (Inclusive). UTC time zone. + """ + class Frequency(proto.Enum): + r"""This ENUM specifies possible frequencies of report + generation. + + Values: + FREQUENCY_UNSPECIFIED (0): + Unspecified. + DAILY (1): + Report will be generated daily. + WEEKLY (2): + Report will be generated weekly. + """ + FREQUENCY_UNSPECIFIED = 0 + DAILY = 1 + WEEKLY = 2 + + frequency: Frequency = proto.Field( + proto.ENUM, + number=1, + enum=Frequency, + ) + start_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=2, + message=date_pb2.Date, + ) + end_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=3, + message=date_pb2.Date, + ) + + +class CSVOptions(proto.Message): + r"""Options to configure CSV formatted reports. + + Attributes: + record_separator (str): + Record separator characters in CSV. + delimiter (str): + Delimiter characters in CSV. + header_required (bool): + If set, will include a header row in the CSV + report. + """ + + record_separator: str = proto.Field( + proto.STRING, + number=1, + ) + delimiter: str = proto.Field( + proto.STRING, + number=2, + ) + header_required: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class ParquetOptions(proto.Message): + r"""Options to configure Parquet formatted reports. + """ + + +class CloudStorageFilters(proto.Message): + r"""Options to filter data on storage systems. + Next ID: 2 + + Attributes: + bucket (str): + Bucket for which the report will be + generated. + """ + + bucket: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CloudStorageDestinationOptions(proto.Message): + r"""Options to store reports in storage systems. + Next ID: 3 + + Attributes: + bucket (str): + Destination bucket. + destination_path (str): + Destination path is the path in the bucket + where the report should be generated. + """ + + bucket: str = proto.Field( + proto.STRING, + number=1, + ) + destination_path: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ObjectMetadataReportOptions(proto.Message): + r"""Report specification for exporting object metadata. + Next ID: 4 + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + metadata_fields (MutableSequence[str]): + Metadata fields to be included in the report. + storage_filters (google.cloud.storageinsights_v1.types.CloudStorageFilters): + Cloud Storage as the storage system. + + This field is a member of `oneof`_ ``filter``. + storage_destination_options (google.cloud.storageinsights_v1.types.CloudStorageDestinationOptions): + Cloud Storage as the storage system. + + This field is a member of `oneof`_ ``destination_options``. + """ + + metadata_fields: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + storage_filters: 'CloudStorageFilters' = proto.Field( + proto.MESSAGE, + number=2, + oneof='filter', + message='CloudStorageFilters', + ) + storage_destination_options: 'CloudStorageDestinationOptions' = proto.Field( + proto.MESSAGE, + number=3, + oneof='destination_options', + message='CloudStorageDestinationOptions', + ) + + +class ReportConfig(proto.Message): + r"""Message describing ReportConfig object. ReportConfig is the + configuration to generate reports. + See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various fields. + Next ID: 12 + + 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): + name of resource. It will be of form + projects//locations//reportConfigs/. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Create time stamp + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Update time stamp + frequency_options (google.cloud.storageinsights_v1.types.FrequencyOptions): + The frequency of report generation. + csv_options (google.cloud.storageinsights_v1.types.CSVOptions): + Options for CSV formatted reports. + + This field is a member of `oneof`_ ``report_format``. + parquet_options (google.cloud.storageinsights_v1.types.ParquetOptions): + Options for Parquet formatted reports. + + This field is a member of `oneof`_ ``report_format``. + object_metadata_report_options (google.cloud.storageinsights_v1.types.ObjectMetadataReportOptions): + Report for exporting object metadata. + + This field is a member of `oneof`_ ``report_kind``. + labels (MutableMapping[str, str]): + Labels as key value pairs + display_name (str): + User provided display name which can be empty + and limited to 256 characters that is editable. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + frequency_options: 'FrequencyOptions' = proto.Field( + proto.MESSAGE, + number=5, + message='FrequencyOptions', + ) + csv_options: 'CSVOptions' = proto.Field( + proto.MESSAGE, + number=6, + oneof='report_format', + message='CSVOptions', + ) + parquet_options: 'ParquetOptions' = proto.Field( + proto.MESSAGE, + number=7, + oneof='report_format', + message='ParquetOptions', + ) + object_metadata_report_options: 'ObjectMetadataReportOptions' = proto.Field( + proto.MESSAGE, + number=8, + oneof='report_kind', + message='ObjectMetadataReportOptions', + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=10, + ) + display_name: str = proto.Field( + proto.STRING, + number=11, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/mypy.ini b/owl-bot-staging/google-cloud-storageinsights/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/noxfile.py b/owl-bot-staging/google-cloud-storageinsights/v1/noxfile.py new file mode 100644 index 000000000000..bace531aed7c --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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", + "3.11", +] + +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.11" + +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/cloud/storageinsights_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--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/google-cloud-storageinsights/v1/samples/generated_samples/snippet_metadata_google.cloud.storageinsights.v1.json b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/snippet_metadata_google.cloud.storageinsights.v1.json new file mode 100644 index 000000000000..7411c6d3c4bf --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/snippet_metadata_google.cloud.storageinsights.v1.json @@ -0,0 +1,1152 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.storageinsights.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-storageinsights", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient", + "shortName": "StorageInsightsAsyncClient" + }, + "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient.create_report_config", + "method": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights.CreateReportConfig", + "service": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights", + "shortName": "StorageInsights" + }, + "shortName": "CreateReportConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storageinsights_v1.types.CreateReportConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "report_config", + "type": "google.cloud.storageinsights_v1.types.ReportConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.storageinsights_v1.types.ReportConfig", + "shortName": "create_report_config" + }, + "description": "Sample for CreateReportConfig", + "file": "storageinsights_v1_generated_storage_insights_create_report_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storageinsights_v1_generated_StorageInsights_CreateReportConfig_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": "storageinsights_v1_generated_storage_insights_create_report_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient", + "shortName": "StorageInsightsClient" + }, + "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient.create_report_config", + "method": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights.CreateReportConfig", + "service": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights", + "shortName": "StorageInsights" + }, + "shortName": "CreateReportConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storageinsights_v1.types.CreateReportConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "report_config", + "type": "google.cloud.storageinsights_v1.types.ReportConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.storageinsights_v1.types.ReportConfig", + "shortName": "create_report_config" + }, + "description": "Sample for CreateReportConfig", + "file": "storageinsights_v1_generated_storage_insights_create_report_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storageinsights_v1_generated_StorageInsights_CreateReportConfig_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": "storageinsights_v1_generated_storage_insights_create_report_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient", + "shortName": "StorageInsightsAsyncClient" + }, + "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient.delete_report_config", + "method": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights.DeleteReportConfig", + "service": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights", + "shortName": "StorageInsights" + }, + "shortName": "DeleteReportConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storageinsights_v1.types.DeleteReportConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_report_config" + }, + "description": "Sample for DeleteReportConfig", + "file": "storageinsights_v1_generated_storage_insights_delete_report_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storageinsights_v1_generated_StorageInsights_DeleteReportConfig_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "storageinsights_v1_generated_storage_insights_delete_report_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient", + "shortName": "StorageInsightsClient" + }, + "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient.delete_report_config", + "method": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights.DeleteReportConfig", + "service": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights", + "shortName": "StorageInsights" + }, + "shortName": "DeleteReportConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storageinsights_v1.types.DeleteReportConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_report_config" + }, + "description": "Sample for DeleteReportConfig", + "file": "storageinsights_v1_generated_storage_insights_delete_report_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storageinsights_v1_generated_StorageInsights_DeleteReportConfig_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "storageinsights_v1_generated_storage_insights_delete_report_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient", + "shortName": "StorageInsightsAsyncClient" + }, + "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient.get_report_config", + "method": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights.GetReportConfig", + "service": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights", + "shortName": "StorageInsights" + }, + "shortName": "GetReportConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storageinsights_v1.types.GetReportConfigRequest" + }, + { + "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.cloud.storageinsights_v1.types.ReportConfig", + "shortName": "get_report_config" + }, + "description": "Sample for GetReportConfig", + "file": "storageinsights_v1_generated_storage_insights_get_report_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storageinsights_v1_generated_StorageInsights_GetReportConfig_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": "storageinsights_v1_generated_storage_insights_get_report_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient", + "shortName": "StorageInsightsClient" + }, + "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient.get_report_config", + "method": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights.GetReportConfig", + "service": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights", + "shortName": "StorageInsights" + }, + "shortName": "GetReportConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storageinsights_v1.types.GetReportConfigRequest" + }, + { + "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.cloud.storageinsights_v1.types.ReportConfig", + "shortName": "get_report_config" + }, + "description": "Sample for GetReportConfig", + "file": "storageinsights_v1_generated_storage_insights_get_report_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storageinsights_v1_generated_StorageInsights_GetReportConfig_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": "storageinsights_v1_generated_storage_insights_get_report_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient", + "shortName": "StorageInsightsAsyncClient" + }, + "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient.get_report_detail", + "method": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights.GetReportDetail", + "service": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights", + "shortName": "StorageInsights" + }, + "shortName": "GetReportDetail" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storageinsights_v1.types.GetReportDetailRequest" + }, + { + "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.cloud.storageinsights_v1.types.ReportDetail", + "shortName": "get_report_detail" + }, + "description": "Sample for GetReportDetail", + "file": "storageinsights_v1_generated_storage_insights_get_report_detail_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storageinsights_v1_generated_StorageInsights_GetReportDetail_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": "storageinsights_v1_generated_storage_insights_get_report_detail_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient", + "shortName": "StorageInsightsClient" + }, + "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient.get_report_detail", + "method": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights.GetReportDetail", + "service": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights", + "shortName": "StorageInsights" + }, + "shortName": "GetReportDetail" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storageinsights_v1.types.GetReportDetailRequest" + }, + { + "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.cloud.storageinsights_v1.types.ReportDetail", + "shortName": "get_report_detail" + }, + "description": "Sample for GetReportDetail", + "file": "storageinsights_v1_generated_storage_insights_get_report_detail_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storageinsights_v1_generated_StorageInsights_GetReportDetail_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": "storageinsights_v1_generated_storage_insights_get_report_detail_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient", + "shortName": "StorageInsightsAsyncClient" + }, + "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient.list_report_configs", + "method": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights.ListReportConfigs", + "service": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights", + "shortName": "StorageInsights" + }, + "shortName": "ListReportConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storageinsights_v1.types.ListReportConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.storageinsights_v1.services.storage_insights.pagers.ListReportConfigsAsyncPager", + "shortName": "list_report_configs" + }, + "description": "Sample for ListReportConfigs", + "file": "storageinsights_v1_generated_storage_insights_list_report_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storageinsights_v1_generated_StorageInsights_ListReportConfigs_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "storageinsights_v1_generated_storage_insights_list_report_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient", + "shortName": "StorageInsightsClient" + }, + "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient.list_report_configs", + "method": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights.ListReportConfigs", + "service": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights", + "shortName": "StorageInsights" + }, + "shortName": "ListReportConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storageinsights_v1.types.ListReportConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.storageinsights_v1.services.storage_insights.pagers.ListReportConfigsPager", + "shortName": "list_report_configs" + }, + "description": "Sample for ListReportConfigs", + "file": "storageinsights_v1_generated_storage_insights_list_report_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storageinsights_v1_generated_StorageInsights_ListReportConfigs_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "storageinsights_v1_generated_storage_insights_list_report_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient", + "shortName": "StorageInsightsAsyncClient" + }, + "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient.list_report_details", + "method": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights.ListReportDetails", + "service": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights", + "shortName": "StorageInsights" + }, + "shortName": "ListReportDetails" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storageinsights_v1.types.ListReportDetailsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.storageinsights_v1.services.storage_insights.pagers.ListReportDetailsAsyncPager", + "shortName": "list_report_details" + }, + "description": "Sample for ListReportDetails", + "file": "storageinsights_v1_generated_storage_insights_list_report_details_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storageinsights_v1_generated_StorageInsights_ListReportDetails_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "storageinsights_v1_generated_storage_insights_list_report_details_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient", + "shortName": "StorageInsightsClient" + }, + "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient.list_report_details", + "method": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights.ListReportDetails", + "service": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights", + "shortName": "StorageInsights" + }, + "shortName": "ListReportDetails" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storageinsights_v1.types.ListReportDetailsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.storageinsights_v1.services.storage_insights.pagers.ListReportDetailsPager", + "shortName": "list_report_details" + }, + "description": "Sample for ListReportDetails", + "file": "storageinsights_v1_generated_storage_insights_list_report_details_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storageinsights_v1_generated_StorageInsights_ListReportDetails_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "storageinsights_v1_generated_storage_insights_list_report_details_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient", + "shortName": "StorageInsightsAsyncClient" + }, + "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient.update_report_config", + "method": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights.UpdateReportConfig", + "service": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights", + "shortName": "StorageInsights" + }, + "shortName": "UpdateReportConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storageinsights_v1.types.UpdateReportConfigRequest" + }, + { + "name": "report_config", + "type": "google.cloud.storageinsights_v1.types.ReportConfig" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.storageinsights_v1.types.ReportConfig", + "shortName": "update_report_config" + }, + "description": "Sample for UpdateReportConfig", + "file": "storageinsights_v1_generated_storage_insights_update_report_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storageinsights_v1_generated_StorageInsights_UpdateReportConfig_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": "storageinsights_v1_generated_storage_insights_update_report_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient", + "shortName": "StorageInsightsClient" + }, + "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient.update_report_config", + "method": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights.UpdateReportConfig", + "service": { + "fullName": "google.cloud.storageinsights.v1.StorageInsights", + "shortName": "StorageInsights" + }, + "shortName": "UpdateReportConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storageinsights_v1.types.UpdateReportConfigRequest" + }, + { + "name": "report_config", + "type": "google.cloud.storageinsights_v1.types.ReportConfig" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.storageinsights_v1.types.ReportConfig", + "shortName": "update_report_config" + }, + "description": "Sample for UpdateReportConfig", + "file": "storageinsights_v1_generated_storage_insights_update_report_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storageinsights_v1_generated_StorageInsights_UpdateReportConfig_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": "storageinsights_v1_generated_storage_insights_update_report_config_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_create_report_config_async.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_create_report_config_async.py new file mode 100644 index 000000000000..53d12ea780f5 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_create_report_config_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 CreateReportConfig +# 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-cloud-storageinsights + + +# [START storageinsights_v1_generated_StorageInsights_CreateReportConfig_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.cloud import storageinsights_v1 + + +async def sample_create_report_config(): + # Create a client + client = storageinsights_v1.StorageInsightsAsyncClient() + + # Initialize request argument(s) + request = storageinsights_v1.CreateReportConfigRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_report_config(request=request) + + # Handle the response + print(response) + +# [END storageinsights_v1_generated_StorageInsights_CreateReportConfig_async] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_create_report_config_sync.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_create_report_config_sync.py new file mode 100644 index 000000000000..3d46d0af8672 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_create_report_config_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 CreateReportConfig +# 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-cloud-storageinsights + + +# [START storageinsights_v1_generated_StorageInsights_CreateReportConfig_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.cloud import storageinsights_v1 + + +def sample_create_report_config(): + # Create a client + client = storageinsights_v1.StorageInsightsClient() + + # Initialize request argument(s) + request = storageinsights_v1.CreateReportConfigRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_report_config(request=request) + + # Handle the response + print(response) + +# [END storageinsights_v1_generated_StorageInsights_CreateReportConfig_sync] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_delete_report_config_async.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_delete_report_config_async.py new file mode 100644 index 000000000000..a9c946397b67 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_delete_report_config_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 DeleteReportConfig +# 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-cloud-storageinsights + + +# [START storageinsights_v1_generated_StorageInsights_DeleteReportConfig_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.cloud import storageinsights_v1 + + +async def sample_delete_report_config(): + # Create a client + client = storageinsights_v1.StorageInsightsAsyncClient() + + # Initialize request argument(s) + request = storageinsights_v1.DeleteReportConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_report_config(request=request) + + +# [END storageinsights_v1_generated_StorageInsights_DeleteReportConfig_async] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_delete_report_config_sync.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_delete_report_config_sync.py new file mode 100644 index 000000000000..17ab407e9252 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_delete_report_config_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 DeleteReportConfig +# 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-cloud-storageinsights + + +# [START storageinsights_v1_generated_StorageInsights_DeleteReportConfig_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.cloud import storageinsights_v1 + + +def sample_delete_report_config(): + # Create a client + client = storageinsights_v1.StorageInsightsClient() + + # Initialize request argument(s) + request = storageinsights_v1.DeleteReportConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_report_config(request=request) + + +# [END storageinsights_v1_generated_StorageInsights_DeleteReportConfig_sync] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_config_async.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_config_async.py new file mode 100644 index 000000000000..8646f2ffa887 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_config_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 GetReportConfig +# 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-cloud-storageinsights + + +# [START storageinsights_v1_generated_StorageInsights_GetReportConfig_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.cloud import storageinsights_v1 + + +async def sample_get_report_config(): + # Create a client + client = storageinsights_v1.StorageInsightsAsyncClient() + + # Initialize request argument(s) + request = storageinsights_v1.GetReportConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_report_config(request=request) + + # Handle the response + print(response) + +# [END storageinsights_v1_generated_StorageInsights_GetReportConfig_async] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_config_sync.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_config_sync.py new file mode 100644 index 000000000000..877b6fb331fb --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_config_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 GetReportConfig +# 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-cloud-storageinsights + + +# [START storageinsights_v1_generated_StorageInsights_GetReportConfig_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.cloud import storageinsights_v1 + + +def sample_get_report_config(): + # Create a client + client = storageinsights_v1.StorageInsightsClient() + + # Initialize request argument(s) + request = storageinsights_v1.GetReportConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_report_config(request=request) + + # Handle the response + print(response) + +# [END storageinsights_v1_generated_StorageInsights_GetReportConfig_sync] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_detail_async.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_detail_async.py new file mode 100644 index 000000000000..3c3631e3d55b --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_detail_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 GetReportDetail +# 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-cloud-storageinsights + + +# [START storageinsights_v1_generated_StorageInsights_GetReportDetail_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.cloud import storageinsights_v1 + + +async def sample_get_report_detail(): + # Create a client + client = storageinsights_v1.StorageInsightsAsyncClient() + + # Initialize request argument(s) + request = storageinsights_v1.GetReportDetailRequest( + name="name_value", + ) + + # Make the request + response = await client.get_report_detail(request=request) + + # Handle the response + print(response) + +# [END storageinsights_v1_generated_StorageInsights_GetReportDetail_async] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_detail_sync.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_detail_sync.py new file mode 100644 index 000000000000..32fab15fd035 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_detail_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 GetReportDetail +# 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-cloud-storageinsights + + +# [START storageinsights_v1_generated_StorageInsights_GetReportDetail_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.cloud import storageinsights_v1 + + +def sample_get_report_detail(): + # Create a client + client = storageinsights_v1.StorageInsightsClient() + + # Initialize request argument(s) + request = storageinsights_v1.GetReportDetailRequest( + name="name_value", + ) + + # Make the request + response = client.get_report_detail(request=request) + + # Handle the response + print(response) + +# [END storageinsights_v1_generated_StorageInsights_GetReportDetail_sync] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_configs_async.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_configs_async.py new file mode 100644 index 000000000000..5e5e6de3caa1 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_configs_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ListReportConfigs +# 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-cloud-storageinsights + + +# [START storageinsights_v1_generated_StorageInsights_ListReportConfigs_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.cloud import storageinsights_v1 + + +async def sample_list_report_configs(): + # Create a client + client = storageinsights_v1.StorageInsightsAsyncClient() + + # Initialize request argument(s) + request = storageinsights_v1.ListReportConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_report_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END storageinsights_v1_generated_StorageInsights_ListReportConfigs_async] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_configs_sync.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_configs_sync.py new file mode 100644 index 000000000000..5b291bac8c4c --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_configs_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ListReportConfigs +# 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-cloud-storageinsights + + +# [START storageinsights_v1_generated_StorageInsights_ListReportConfigs_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.cloud import storageinsights_v1 + + +def sample_list_report_configs(): + # Create a client + client = storageinsights_v1.StorageInsightsClient() + + # Initialize request argument(s) + request = storageinsights_v1.ListReportConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_report_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END storageinsights_v1_generated_StorageInsights_ListReportConfigs_sync] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_details_async.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_details_async.py new file mode 100644 index 000000000000..6d922f937cfa --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_details_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ListReportDetails +# 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-cloud-storageinsights + + +# [START storageinsights_v1_generated_StorageInsights_ListReportDetails_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.cloud import storageinsights_v1 + + +async def sample_list_report_details(): + # Create a client + client = storageinsights_v1.StorageInsightsAsyncClient() + + # Initialize request argument(s) + request = storageinsights_v1.ListReportDetailsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_report_details(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END storageinsights_v1_generated_StorageInsights_ListReportDetails_async] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_details_sync.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_details_sync.py new file mode 100644 index 000000000000..fcb37ad4a4ec --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_details_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ListReportDetails +# 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-cloud-storageinsights + + +# [START storageinsights_v1_generated_StorageInsights_ListReportDetails_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.cloud import storageinsights_v1 + + +def sample_list_report_details(): + # Create a client + client = storageinsights_v1.StorageInsightsClient() + + # Initialize request argument(s) + request = storageinsights_v1.ListReportDetailsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_report_details(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END storageinsights_v1_generated_StorageInsights_ListReportDetails_sync] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_update_report_config_async.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_update_report_config_async.py new file mode 100644 index 000000000000..a874104b638e --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_update_report_config_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 UpdateReportConfig +# 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-cloud-storageinsights + + +# [START storageinsights_v1_generated_StorageInsights_UpdateReportConfig_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.cloud import storageinsights_v1 + + +async def sample_update_report_config(): + # Create a client + client = storageinsights_v1.StorageInsightsAsyncClient() + + # Initialize request argument(s) + request = storageinsights_v1.UpdateReportConfigRequest( + ) + + # Make the request + response = await client.update_report_config(request=request) + + # Handle the response + print(response) + +# [END storageinsights_v1_generated_StorageInsights_UpdateReportConfig_async] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_update_report_config_sync.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_update_report_config_sync.py new file mode 100644 index 000000000000..03071db6140e --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_update_report_config_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 UpdateReportConfig +# 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-cloud-storageinsights + + +# [START storageinsights_v1_generated_StorageInsights_UpdateReportConfig_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.cloud import storageinsights_v1 + + +def sample_update_report_config(): + # Create a client + client = storageinsights_v1.StorageInsightsClient() + + # Initialize request argument(s) + request = storageinsights_v1.UpdateReportConfigRequest( + ) + + # Make the request + response = client.update_report_config(request=request) + + # Handle the response + print(response) + +# [END storageinsights_v1_generated_StorageInsights_UpdateReportConfig_sync] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/scripts/fixup_storageinsights_v1_keywords.py b/owl-bot-staging/google-cloud-storageinsights/v1/scripts/fixup_storageinsights_v1_keywords.py new file mode 100644 index 000000000000..ea93709df957 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/scripts/fixup_storageinsights_v1_keywords.py @@ -0,0 +1,182 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 storageinsightsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_report_config': ('parent', 'report_config', 'request_id', ), + 'delete_report_config': ('name', 'force', 'request_id', ), + 'get_report_config': ('name', ), + 'get_report_detail': ('name', ), + 'list_report_configs': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_report_details': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'update_report_config': ('update_mask', 'report_config', 'request_id', ), + } + + 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=storageinsightsCallTransformer(), +): + """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 storageinsights client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/setup.py b/owl-bot-staging/google-cloud-storageinsights/v1/setup.py new file mode 100644 index 000000000000..bce5e7831667 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/setup.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-cloud-storageinsights' + + +description = "Google Cloud Storageinsights API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/storageinsights/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.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "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-storageinsights" + +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", "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", + "Programming Language :: Python :: 3.11", + "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/google-cloud-storageinsights/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..6c44adfea7ee --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.7.txt @@ -0,0 +1,9 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/tests/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/tests/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/storageinsights_v1/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/storageinsights_v1/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/storageinsights_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/storageinsights_v1/test_storage_insights.py b/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/storageinsights_v1/test_storage_insights.py new file mode 100644 index 000000000000..fcc37c2e1b3e --- /dev/null +++ b/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/storageinsights_v1/test_storage_insights.py @@ -0,0 +1,6142 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.storageinsights_v1.services.storage_insights import StorageInsightsAsyncClient +from google.cloud.storageinsights_v1.services.storage_insights import StorageInsightsClient +from google.cloud.storageinsights_v1.services.storage_insights import pagers +from google.cloud.storageinsights_v1.services.storage_insights import transports +from google.cloud.storageinsights_v1.types import storageinsights +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +from google.type import datetime_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 StorageInsightsClient._get_default_mtls_endpoint(None) is None + assert StorageInsightsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert StorageInsightsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert StorageInsightsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert StorageInsightsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert StorageInsightsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (StorageInsightsClient, "grpc"), + (StorageInsightsAsyncClient, "grpc_asyncio"), + (StorageInsightsClient, "rest"), +]) +def test_storage_insights_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 == ( + 'storageinsights.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://storageinsights.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.StorageInsightsGrpcTransport, "grpc"), + (transports.StorageInsightsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.StorageInsightsRestTransport, "rest"), +]) +def test_storage_insights_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", [ + (StorageInsightsClient, "grpc"), + (StorageInsightsAsyncClient, "grpc_asyncio"), + (StorageInsightsClient, "rest"), +]) +def test_storage_insights_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 == ( + 'storageinsights.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://storageinsights.googleapis.com' + ) + + +def test_storage_insights_client_get_transport_class(): + transport = StorageInsightsClient.get_transport_class() + available_transports = [ + transports.StorageInsightsGrpcTransport, + transports.StorageInsightsRestTransport, + ] + assert transport in available_transports + + transport = StorageInsightsClient.get_transport_class("grpc") + assert transport == transports.StorageInsightsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StorageInsightsClient, transports.StorageInsightsGrpcTransport, "grpc"), + (StorageInsightsAsyncClient, transports.StorageInsightsGrpcAsyncIOTransport, "grpc_asyncio"), + (StorageInsightsClient, transports.StorageInsightsRestTransport, "rest"), +]) +@mock.patch.object(StorageInsightsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StorageInsightsClient)) +@mock.patch.object(StorageInsightsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StorageInsightsAsyncClient)) +def test_storage_insights_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(StorageInsightsClient, '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(StorageInsightsClient, '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", [ + (StorageInsightsClient, transports.StorageInsightsGrpcTransport, "grpc", "true"), + (StorageInsightsAsyncClient, transports.StorageInsightsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (StorageInsightsClient, transports.StorageInsightsGrpcTransport, "grpc", "false"), + (StorageInsightsAsyncClient, transports.StorageInsightsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (StorageInsightsClient, transports.StorageInsightsRestTransport, "rest", "true"), + (StorageInsightsClient, transports.StorageInsightsRestTransport, "rest", "false"), +]) +@mock.patch.object(StorageInsightsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StorageInsightsClient)) +@mock.patch.object(StorageInsightsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StorageInsightsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_storage_insights_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", [ + StorageInsightsClient, StorageInsightsAsyncClient +]) +@mock.patch.object(StorageInsightsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StorageInsightsClient)) +@mock.patch.object(StorageInsightsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StorageInsightsAsyncClient)) +def test_storage_insights_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", [ + (StorageInsightsClient, transports.StorageInsightsGrpcTransport, "grpc"), + (StorageInsightsAsyncClient, transports.StorageInsightsGrpcAsyncIOTransport, "grpc_asyncio"), + (StorageInsightsClient, transports.StorageInsightsRestTransport, "rest"), +]) +def test_storage_insights_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", [ + (StorageInsightsClient, transports.StorageInsightsGrpcTransport, "grpc", grpc_helpers), + (StorageInsightsAsyncClient, transports.StorageInsightsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (StorageInsightsClient, transports.StorageInsightsRestTransport, "rest", None), +]) +def test_storage_insights_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_storage_insights_client_client_options_from_dict(): + with mock.patch('google.cloud.storageinsights_v1.services.storage_insights.transports.StorageInsightsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = StorageInsightsClient( + 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", [ + (StorageInsightsClient, transports.StorageInsightsGrpcTransport, "grpc", grpc_helpers), + (StorageInsightsAsyncClient, transports.StorageInsightsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_storage_insights_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( + "storageinsights.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="storageinsights.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + storageinsights.ListReportConfigsRequest, + dict, +]) +def test_list_report_configs(request_type, transport: str = 'grpc'): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = storageinsights.ListReportConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_report_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.ListReportConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReportConfigsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_report_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_configs), + '__call__') as call: + client.list_report_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.ListReportConfigsRequest() + +@pytest.mark.asyncio +async def test_list_report_configs_async(transport: str = 'grpc_asyncio', request_type=storageinsights.ListReportConfigsRequest): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ListReportConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_report_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.ListReportConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReportConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_report_configs_async_from_dict(): + await test_list_report_configs_async(request_type=dict) + + +def test_list_report_configs_field_headers(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storageinsights.ListReportConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_configs), + '__call__') as call: + call.return_value = storageinsights.ListReportConfigsResponse() + client.list_report_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_report_configs_field_headers_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storageinsights.ListReportConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ListReportConfigsResponse()) + await client.list_report_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_report_configs_flattened(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = storageinsights.ListReportConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_report_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_report_configs_flattened_error(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_report_configs( + storageinsights.ListReportConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_report_configs_flattened_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = storageinsights.ListReportConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ListReportConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_report_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_report_configs_flattened_error_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_report_configs( + storageinsights.ListReportConfigsRequest(), + parent='parent_value', + ) + + +def test_list_report_configs_pager(transport_name: str = "grpc"): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + storageinsights.ListReportConfigsResponse( + report_configs=[ + storageinsights.ReportConfig(), + storageinsights.ReportConfig(), + storageinsights.ReportConfig(), + ], + next_page_token='abc', + ), + storageinsights.ListReportConfigsResponse( + report_configs=[], + next_page_token='def', + ), + storageinsights.ListReportConfigsResponse( + report_configs=[ + storageinsights.ReportConfig(), + ], + next_page_token='ghi', + ), + storageinsights.ListReportConfigsResponse( + report_configs=[ + storageinsights.ReportConfig(), + storageinsights.ReportConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_report_configs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, storageinsights.ReportConfig) + for i in results) +def test_list_report_configs_pages(transport_name: str = "grpc"): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + storageinsights.ListReportConfigsResponse( + report_configs=[ + storageinsights.ReportConfig(), + storageinsights.ReportConfig(), + storageinsights.ReportConfig(), + ], + next_page_token='abc', + ), + storageinsights.ListReportConfigsResponse( + report_configs=[], + next_page_token='def', + ), + storageinsights.ListReportConfigsResponse( + report_configs=[ + storageinsights.ReportConfig(), + ], + next_page_token='ghi', + ), + storageinsights.ListReportConfigsResponse( + report_configs=[ + storageinsights.ReportConfig(), + storageinsights.ReportConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_report_configs(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_report_configs_async_pager(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + storageinsights.ListReportConfigsResponse( + report_configs=[ + storageinsights.ReportConfig(), + storageinsights.ReportConfig(), + storageinsights.ReportConfig(), + ], + next_page_token='abc', + ), + storageinsights.ListReportConfigsResponse( + report_configs=[], + next_page_token='def', + ), + storageinsights.ListReportConfigsResponse( + report_configs=[ + storageinsights.ReportConfig(), + ], + next_page_token='ghi', + ), + storageinsights.ListReportConfigsResponse( + report_configs=[ + storageinsights.ReportConfig(), + storageinsights.ReportConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_report_configs(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, storageinsights.ReportConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_report_configs_async_pages(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + storageinsights.ListReportConfigsResponse( + report_configs=[ + storageinsights.ReportConfig(), + storageinsights.ReportConfig(), + storageinsights.ReportConfig(), + ], + next_page_token='abc', + ), + storageinsights.ListReportConfigsResponse( + report_configs=[], + next_page_token='def', + ), + storageinsights.ListReportConfigsResponse( + report_configs=[ + storageinsights.ReportConfig(), + ], + next_page_token='ghi', + ), + storageinsights.ListReportConfigsResponse( + report_configs=[ + storageinsights.ReportConfig(), + storageinsights.ReportConfig(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_report_configs(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + storageinsights.GetReportConfigRequest, + dict, +]) +def test_get_report_config(request_type, transport: str = 'grpc'): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_report_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = storageinsights.ReportConfig( + name='name_value', + display_name='display_name_value', + ) + response = client.get_report_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.GetReportConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, storageinsights.ReportConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_get_report_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageInsightsClient( + credentials=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_report_config), + '__call__') as call: + client.get_report_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.GetReportConfigRequest() + +@pytest.mark.asyncio +async def test_get_report_config_async(transport: str = 'grpc_asyncio', request_type=storageinsights.GetReportConfigRequest): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_report_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportConfig( + name='name_value', + display_name='display_name_value', + )) + response = await client.get_report_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.GetReportConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, storageinsights.ReportConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_get_report_config_async_from_dict(): + await test_get_report_config_async(request_type=dict) + + +def test_get_report_config_field_headers(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storageinsights.GetReportConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_report_config), + '__call__') as call: + call.return_value = storageinsights.ReportConfig() + client.get_report_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_report_config_field_headers_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storageinsights.GetReportConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_report_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportConfig()) + await client.get_report_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_report_config_flattened(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_report_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = storageinsights.ReportConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_report_config( + 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_report_config_flattened_error(): + client = StorageInsightsClient( + credentials=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_report_config( + storageinsights.GetReportConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_report_config_flattened_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_report_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = storageinsights.ReportConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_report_config( + 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_report_config_flattened_error_async(): + client = StorageInsightsAsyncClient( + credentials=ga_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_report_config( + storageinsights.GetReportConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + storageinsights.CreateReportConfigRequest, + dict, +]) +def test_create_report_config(request_type, transport: str = 'grpc'): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_report_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = storageinsights.ReportConfig( + name='name_value', + display_name='display_name_value', + ) + response = client.create_report_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.CreateReportConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, storageinsights.ReportConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_create_report_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_report_config), + '__call__') as call: + client.create_report_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.CreateReportConfigRequest() + +@pytest.mark.asyncio +async def test_create_report_config_async(transport: str = 'grpc_asyncio', request_type=storageinsights.CreateReportConfigRequest): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_report_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportConfig( + name='name_value', + display_name='display_name_value', + )) + response = await client.create_report_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.CreateReportConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, storageinsights.ReportConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_create_report_config_async_from_dict(): + await test_create_report_config_async(request_type=dict) + + +def test_create_report_config_field_headers(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storageinsights.CreateReportConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_report_config), + '__call__') as call: + call.return_value = storageinsights.ReportConfig() + client.create_report_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_report_config_field_headers_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storageinsights.CreateReportConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_report_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportConfig()) + await client.create_report_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_report_config_flattened(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_report_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = storageinsights.ReportConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_report_config( + parent='parent_value', + report_config=storageinsights.ReportConfig(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].report_config + mock_val = storageinsights.ReportConfig(name='name_value') + assert arg == mock_val + + +def test_create_report_config_flattened_error(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_report_config( + storageinsights.CreateReportConfigRequest(), + parent='parent_value', + report_config=storageinsights.ReportConfig(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_report_config_flattened_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_report_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = storageinsights.ReportConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_report_config( + parent='parent_value', + report_config=storageinsights.ReportConfig(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].report_config + mock_val = storageinsights.ReportConfig(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_report_config_flattened_error_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_report_config( + storageinsights.CreateReportConfigRequest(), + parent='parent_value', + report_config=storageinsights.ReportConfig(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + storageinsights.UpdateReportConfigRequest, + dict, +]) +def test_update_report_config(request_type, transport: str = 'grpc'): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_report_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = storageinsights.ReportConfig( + name='name_value', + display_name='display_name_value', + ) + response = client.update_report_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.UpdateReportConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, storageinsights.ReportConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_update_report_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_report_config), + '__call__') as call: + client.update_report_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.UpdateReportConfigRequest() + +@pytest.mark.asyncio +async def test_update_report_config_async(transport: str = 'grpc_asyncio', request_type=storageinsights.UpdateReportConfigRequest): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_report_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportConfig( + name='name_value', + display_name='display_name_value', + )) + response = await client.update_report_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.UpdateReportConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, storageinsights.ReportConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_update_report_config_async_from_dict(): + await test_update_report_config_async(request_type=dict) + + +def test_update_report_config_field_headers(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storageinsights.UpdateReportConfigRequest() + + request.report_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_report_config), + '__call__') as call: + call.return_value = storageinsights.ReportConfig() + client.update_report_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'report_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_report_config_field_headers_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storageinsights.UpdateReportConfigRequest() + + request.report_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_report_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportConfig()) + await client.update_report_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'report_config.name=name_value', + ) in kw['metadata'] + + +def test_update_report_config_flattened(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_report_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = storageinsights.ReportConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_report_config( + report_config=storageinsights.ReportConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].report_config + mock_val = storageinsights.ReportConfig(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_report_config_flattened_error(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_report_config( + storageinsights.UpdateReportConfigRequest(), + report_config=storageinsights.ReportConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_report_config_flattened_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_report_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = storageinsights.ReportConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_report_config( + report_config=storageinsights.ReportConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].report_config + mock_val = storageinsights.ReportConfig(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_report_config_flattened_error_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_report_config( + storageinsights.UpdateReportConfigRequest(), + report_config=storageinsights.ReportConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + storageinsights.DeleteReportConfigRequest, + dict, +]) +def test_delete_report_config(request_type, transport: str = 'grpc'): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_report_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_report_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.DeleteReportConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_report_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_report_config), + '__call__') as call: + client.delete_report_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.DeleteReportConfigRequest() + +@pytest.mark.asyncio +async def test_delete_report_config_async(transport: str = 'grpc_asyncio', request_type=storageinsights.DeleteReportConfigRequest): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_report_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_report_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.DeleteReportConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_report_config_async_from_dict(): + await test_delete_report_config_async(request_type=dict) + + +def test_delete_report_config_field_headers(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storageinsights.DeleteReportConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_report_config), + '__call__') as call: + call.return_value = None + client.delete_report_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_report_config_field_headers_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storageinsights.DeleteReportConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_report_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_report_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_report_config_flattened(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_report_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_report_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_report_config_flattened_error(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_report_config( + storageinsights.DeleteReportConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_report_config_flattened_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_report_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_report_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_report_config_flattened_error_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_report_config( + storageinsights.DeleteReportConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + storageinsights.ListReportDetailsRequest, + dict, +]) +def test_list_report_details(request_type, transport: str = 'grpc'): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_details), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = storageinsights.ListReportDetailsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_report_details(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.ListReportDetailsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReportDetailsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_report_details_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_details), + '__call__') as call: + client.list_report_details() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.ListReportDetailsRequest() + +@pytest.mark.asyncio +async def test_list_report_details_async(transport: str = 'grpc_asyncio', request_type=storageinsights.ListReportDetailsRequest): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_details), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ListReportDetailsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_report_details(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.ListReportDetailsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReportDetailsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_report_details_async_from_dict(): + await test_list_report_details_async(request_type=dict) + + +def test_list_report_details_field_headers(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storageinsights.ListReportDetailsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_details), + '__call__') as call: + call.return_value = storageinsights.ListReportDetailsResponse() + client.list_report_details(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_report_details_field_headers_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storageinsights.ListReportDetailsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_details), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ListReportDetailsResponse()) + await client.list_report_details(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_report_details_flattened(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_details), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = storageinsights.ListReportDetailsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_report_details( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_report_details_flattened_error(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_report_details( + storageinsights.ListReportDetailsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_report_details_flattened_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_details), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = storageinsights.ListReportDetailsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ListReportDetailsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_report_details( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_report_details_flattened_error_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_report_details( + storageinsights.ListReportDetailsRequest(), + parent='parent_value', + ) + + +def test_list_report_details_pager(transport_name: str = "grpc"): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_details), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + storageinsights.ListReportDetailsResponse( + report_details=[ + storageinsights.ReportDetail(), + storageinsights.ReportDetail(), + storageinsights.ReportDetail(), + ], + next_page_token='abc', + ), + storageinsights.ListReportDetailsResponse( + report_details=[], + next_page_token='def', + ), + storageinsights.ListReportDetailsResponse( + report_details=[ + storageinsights.ReportDetail(), + ], + next_page_token='ghi', + ), + storageinsights.ListReportDetailsResponse( + report_details=[ + storageinsights.ReportDetail(), + storageinsights.ReportDetail(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_report_details(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, storageinsights.ReportDetail) + for i in results) +def test_list_report_details_pages(transport_name: str = "grpc"): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_details), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + storageinsights.ListReportDetailsResponse( + report_details=[ + storageinsights.ReportDetail(), + storageinsights.ReportDetail(), + storageinsights.ReportDetail(), + ], + next_page_token='abc', + ), + storageinsights.ListReportDetailsResponse( + report_details=[], + next_page_token='def', + ), + storageinsights.ListReportDetailsResponse( + report_details=[ + storageinsights.ReportDetail(), + ], + next_page_token='ghi', + ), + storageinsights.ListReportDetailsResponse( + report_details=[ + storageinsights.ReportDetail(), + storageinsights.ReportDetail(), + ], + ), + RuntimeError, + ) + pages = list(client.list_report_details(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_report_details_async_pager(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_details), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + storageinsights.ListReportDetailsResponse( + report_details=[ + storageinsights.ReportDetail(), + storageinsights.ReportDetail(), + storageinsights.ReportDetail(), + ], + next_page_token='abc', + ), + storageinsights.ListReportDetailsResponse( + report_details=[], + next_page_token='def', + ), + storageinsights.ListReportDetailsResponse( + report_details=[ + storageinsights.ReportDetail(), + ], + next_page_token='ghi', + ), + storageinsights.ListReportDetailsResponse( + report_details=[ + storageinsights.ReportDetail(), + storageinsights.ReportDetail(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_report_details(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, storageinsights.ReportDetail) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_report_details_async_pages(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_report_details), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + storageinsights.ListReportDetailsResponse( + report_details=[ + storageinsights.ReportDetail(), + storageinsights.ReportDetail(), + storageinsights.ReportDetail(), + ], + next_page_token='abc', + ), + storageinsights.ListReportDetailsResponse( + report_details=[], + next_page_token='def', + ), + storageinsights.ListReportDetailsResponse( + report_details=[ + storageinsights.ReportDetail(), + ], + next_page_token='ghi', + ), + storageinsights.ListReportDetailsResponse( + report_details=[ + storageinsights.ReportDetail(), + storageinsights.ReportDetail(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_report_details(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + storageinsights.GetReportDetailRequest, + dict, +]) +def test_get_report_detail(request_type, transport: str = 'grpc'): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_report_detail), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = storageinsights.ReportDetail( + name='name_value', + report_path_prefix='report_path_prefix_value', + shards_count=1293, + ) + response = client.get_report_detail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.GetReportDetailRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, storageinsights.ReportDetail) + assert response.name == 'name_value' + assert response.report_path_prefix == 'report_path_prefix_value' + assert response.shards_count == 1293 + + +def test_get_report_detail_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageInsightsClient( + credentials=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_report_detail), + '__call__') as call: + client.get_report_detail() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.GetReportDetailRequest() + +@pytest.mark.asyncio +async def test_get_report_detail_async(transport: str = 'grpc_asyncio', request_type=storageinsights.GetReportDetailRequest): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_report_detail), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportDetail( + name='name_value', + report_path_prefix='report_path_prefix_value', + shards_count=1293, + )) + response = await client.get_report_detail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == storageinsights.GetReportDetailRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, storageinsights.ReportDetail) + assert response.name == 'name_value' + assert response.report_path_prefix == 'report_path_prefix_value' + assert response.shards_count == 1293 + + +@pytest.mark.asyncio +async def test_get_report_detail_async_from_dict(): + await test_get_report_detail_async(request_type=dict) + + +def test_get_report_detail_field_headers(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storageinsights.GetReportDetailRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_report_detail), + '__call__') as call: + call.return_value = storageinsights.ReportDetail() + client.get_report_detail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_report_detail_field_headers_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storageinsights.GetReportDetailRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_report_detail), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportDetail()) + await client.get_report_detail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_report_detail_flattened(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_report_detail), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = storageinsights.ReportDetail() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_report_detail( + 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_report_detail_flattened_error(): + client = StorageInsightsClient( + credentials=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_report_detail( + storageinsights.GetReportDetailRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_report_detail_flattened_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_report_detail), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = storageinsights.ReportDetail() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportDetail()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_report_detail( + 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_report_detail_flattened_error_async(): + client = StorageInsightsAsyncClient( + credentials=ga_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_report_detail( + storageinsights.GetReportDetailRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + storageinsights.ListReportConfigsRequest, + dict, +]) +def test_list_report_configs_rest(request_type): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = storageinsights.ListReportConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = storageinsights.ListReportConfigsResponse.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.list_report_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReportConfigsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_report_configs_rest_required_fields(request_type=storageinsights.ListReportConfigsRequest): + transport_class = transports.StorageInsightsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + 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()).list_report_configs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_report_configs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = storageinsights.ListReportConfigsResponse() + # 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 = storageinsights.ListReportConfigsResponse.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.list_report_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_report_configs_rest_unset_required_fields(): + transport = transports.StorageInsightsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_report_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_report_configs_rest_interceptors(null_interceptor): + transport = transports.StorageInsightsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageInsightsRestInterceptor(), + ) + client = StorageInsightsClient(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.StorageInsightsRestInterceptor, "post_list_report_configs") as post, \ + mock.patch.object(transports.StorageInsightsRestInterceptor, "pre_list_report_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = storageinsights.ListReportConfigsRequest.pb(storageinsights.ListReportConfigsRequest()) + 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 = storageinsights.ListReportConfigsResponse.to_json(storageinsights.ListReportConfigsResponse()) + + request = storageinsights.ListReportConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = storageinsights.ListReportConfigsResponse() + + client.list_report_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_report_configs_rest_bad_request(transport: str = 'rest', request_type=storageinsights.ListReportConfigsRequest): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_report_configs(request) + + +def test_list_report_configs_rest_flattened(): + client = StorageInsightsClient( + 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 = storageinsights.ListReportConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = storageinsights.ListReportConfigsResponse.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.list_report_configs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/reportConfigs" % client.transport._host, args[1]) + + +def test_list_report_configs_rest_flattened_error(transport: str = 'rest'): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_report_configs( + storageinsights.ListReportConfigsRequest(), + parent='parent_value', + ) + + +def test_list_report_configs_rest_pager(transport: str = 'rest'): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + storageinsights.ListReportConfigsResponse( + report_configs=[ + storageinsights.ReportConfig(), + storageinsights.ReportConfig(), + storageinsights.ReportConfig(), + ], + next_page_token='abc', + ), + storageinsights.ListReportConfigsResponse( + report_configs=[], + next_page_token='def', + ), + storageinsights.ListReportConfigsResponse( + report_configs=[ + storageinsights.ReportConfig(), + ], + next_page_token='ghi', + ), + storageinsights.ListReportConfigsResponse( + report_configs=[ + storageinsights.ReportConfig(), + storageinsights.ReportConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(storageinsights.ListReportConfigsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_report_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, storageinsights.ReportConfig) + for i in results) + + pages = list(client.list_report_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + storageinsights.GetReportConfigRequest, + dict, +]) +def test_get_report_config_rest(request_type): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = storageinsights.ReportConfig( + name='name_value', + display_name='display_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = storageinsights.ReportConfig.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_report_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, storageinsights.ReportConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_get_report_config_rest_required_fields(request_type=storageinsights.GetReportConfigRequest): + transport_class = transports.StorageInsightsRestTransport + + 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_report_config._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_report_config._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 = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = storageinsights.ReportConfig() + # 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 = storageinsights.ReportConfig.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_report_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_report_config_rest_unset_required_fields(): + transport = transports.StorageInsightsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_report_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_report_config_rest_interceptors(null_interceptor): + transport = transports.StorageInsightsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageInsightsRestInterceptor(), + ) + client = StorageInsightsClient(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.StorageInsightsRestInterceptor, "post_get_report_config") as post, \ + mock.patch.object(transports.StorageInsightsRestInterceptor, "pre_get_report_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = storageinsights.GetReportConfigRequest.pb(storageinsights.GetReportConfigRequest()) + 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 = storageinsights.ReportConfig.to_json(storageinsights.ReportConfig()) + + request = storageinsights.GetReportConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = storageinsights.ReportConfig() + + client.get_report_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_report_config_rest_bad_request(transport: str = 'rest', request_type=storageinsights.GetReportConfigRequest): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_report_config(request) + + +def test_get_report_config_rest_flattened(): + client = StorageInsightsClient( + 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 = storageinsights.ReportConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = storageinsights.ReportConfig.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_report_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/reportConfigs/*}" % client.transport._host, args[1]) + + +def test_get_report_config_rest_flattened_error(transport: str = 'rest'): + client = StorageInsightsClient( + 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_report_config( + storageinsights.GetReportConfigRequest(), + name='name_value', + ) + + +def test_get_report_config_rest_error(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + storageinsights.CreateReportConfigRequest, + dict, +]) +def test_create_report_config_rest(request_type): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["report_config"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'frequency_options': {'frequency': 1, 'start_date': {'year': 433, 'month': 550, 'day': 318}, 'end_date': {}}, 'csv_options': {'record_separator': 'record_separator_value', 'delimiter': 'delimiter_value', 'header_required': True}, 'parquet_options': {}, 'object_metadata_report_options': {'metadata_fields': ['metadata_fields_value1', 'metadata_fields_value2'], 'storage_filters': {'bucket': 'bucket_value'}, 'storage_destination_options': {'bucket': 'bucket_value', 'destination_path': 'destination_path_value'}}, 'labels': {}, 'display_name': 'display_name_value'} + 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 = storageinsights.ReportConfig( + name='name_value', + display_name='display_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = storageinsights.ReportConfig.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.create_report_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, storageinsights.ReportConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_create_report_config_rest_required_fields(request_type=storageinsights.CreateReportConfigRequest): + transport_class = transports.StorageInsightsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + 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()).create_report_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_report_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = storageinsights.ReportConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = storageinsights.ReportConfig.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.create_report_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_report_config_rest_unset_required_fields(): + transport = transports.StorageInsightsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_report_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("parent", "reportConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_report_config_rest_interceptors(null_interceptor): + transport = transports.StorageInsightsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageInsightsRestInterceptor(), + ) + client = StorageInsightsClient(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.StorageInsightsRestInterceptor, "post_create_report_config") as post, \ + mock.patch.object(transports.StorageInsightsRestInterceptor, "pre_create_report_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = storageinsights.CreateReportConfigRequest.pb(storageinsights.CreateReportConfigRequest()) + 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 = storageinsights.ReportConfig.to_json(storageinsights.ReportConfig()) + + request = storageinsights.CreateReportConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = storageinsights.ReportConfig() + + client.create_report_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_report_config_rest_bad_request(transport: str = 'rest', request_type=storageinsights.CreateReportConfigRequest): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["report_config"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'frequency_options': {'frequency': 1, 'start_date': {'year': 433, 'month': 550, 'day': 318}, 'end_date': {}}, 'csv_options': {'record_separator': 'record_separator_value', 'delimiter': 'delimiter_value', 'header_required': True}, 'parquet_options': {}, 'object_metadata_report_options': {'metadata_fields': ['metadata_fields_value1', 'metadata_fields_value2'], 'storage_filters': {'bucket': 'bucket_value'}, 'storage_destination_options': {'bucket': 'bucket_value', 'destination_path': 'destination_path_value'}}, 'labels': {}, 'display_name': 'display_name_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_report_config(request) + + +def test_create_report_config_rest_flattened(): + client = StorageInsightsClient( + 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 = storageinsights.ReportConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + report_config=storageinsights.ReportConfig(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 = storageinsights.ReportConfig.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.create_report_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/reportConfigs" % client.transport._host, args[1]) + + +def test_create_report_config_rest_flattened_error(transport: str = 'rest'): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_report_config( + storageinsights.CreateReportConfigRequest(), + parent='parent_value', + report_config=storageinsights.ReportConfig(name='name_value'), + ) + + +def test_create_report_config_rest_error(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + storageinsights.UpdateReportConfigRequest, + dict, +]) +def test_update_report_config_rest(request_type): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'report_config': {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3'}} + request_init["report_config"] = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'frequency_options': {'frequency': 1, 'start_date': {'year': 433, 'month': 550, 'day': 318}, 'end_date': {}}, 'csv_options': {'record_separator': 'record_separator_value', 'delimiter': 'delimiter_value', 'header_required': True}, 'parquet_options': {}, 'object_metadata_report_options': {'metadata_fields': ['metadata_fields_value1', 'metadata_fields_value2'], 'storage_filters': {'bucket': 'bucket_value'}, 'storage_destination_options': {'bucket': 'bucket_value', 'destination_path': 'destination_path_value'}}, 'labels': {}, 'display_name': 'display_name_value'} + 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 = storageinsights.ReportConfig( + name='name_value', + display_name='display_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = storageinsights.ReportConfig.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.update_report_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, storageinsights.ReportConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_update_report_config_rest_required_fields(request_type=storageinsights.UpdateReportConfigRequest): + transport_class = transports.StorageInsightsRestTransport + + request_init = {} + 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()).update_report_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_report_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = storageinsights.ReportConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = storageinsights.ReportConfig.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.update_report_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_report_config_rest_unset_required_fields(): + transport = transports.StorageInsightsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_report_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "reportConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_report_config_rest_interceptors(null_interceptor): + transport = transports.StorageInsightsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageInsightsRestInterceptor(), + ) + client = StorageInsightsClient(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.StorageInsightsRestInterceptor, "post_update_report_config") as post, \ + mock.patch.object(transports.StorageInsightsRestInterceptor, "pre_update_report_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = storageinsights.UpdateReportConfigRequest.pb(storageinsights.UpdateReportConfigRequest()) + 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 = storageinsights.ReportConfig.to_json(storageinsights.ReportConfig()) + + request = storageinsights.UpdateReportConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = storageinsights.ReportConfig() + + client.update_report_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_report_config_rest_bad_request(transport: str = 'rest', request_type=storageinsights.UpdateReportConfigRequest): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'report_config': {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3'}} + request_init["report_config"] = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'frequency_options': {'frequency': 1, 'start_date': {'year': 433, 'month': 550, 'day': 318}, 'end_date': {}}, 'csv_options': {'record_separator': 'record_separator_value', 'delimiter': 'delimiter_value', 'header_required': True}, 'parquet_options': {}, 'object_metadata_report_options': {'metadata_fields': ['metadata_fields_value1', 'metadata_fields_value2'], 'storage_filters': {'bucket': 'bucket_value'}, 'storage_destination_options': {'bucket': 'bucket_value', 'destination_path': 'destination_path_value'}}, 'labels': {}, 'display_name': 'display_name_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_report_config(request) + + +def test_update_report_config_rest_flattened(): + client = StorageInsightsClient( + 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 = storageinsights.ReportConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'report_config': {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + report_config=storageinsights.ReportConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = storageinsights.ReportConfig.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.update_report_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{report_config.name=projects/*/locations/*/reportConfigs/*}" % client.transport._host, args[1]) + + +def test_update_report_config_rest_flattened_error(transport: str = 'rest'): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_report_config( + storageinsights.UpdateReportConfigRequest(), + report_config=storageinsights.ReportConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_report_config_rest_error(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + storageinsights.DeleteReportConfigRequest, + dict, +]) +def test_delete_report_config_rest(request_type): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_report_config(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_report_config_rest_required_fields(request_type=storageinsights.DeleteReportConfigRequest): + transport_class = transports.StorageInsightsRestTransport + + 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()).delete_report_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_report_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force", "request_id", )) + 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 = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_report_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_report_config_rest_unset_required_fields(): + transport = transports.StorageInsightsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_report_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force", "requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_report_config_rest_interceptors(null_interceptor): + transport = transports.StorageInsightsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageInsightsRestInterceptor(), + ) + client = StorageInsightsClient(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.StorageInsightsRestInterceptor, "pre_delete_report_config") as pre: + pre.assert_not_called() + pb_message = storageinsights.DeleteReportConfigRequest.pb(storageinsights.DeleteReportConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = storageinsights.DeleteReportConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_report_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_report_config_rest_bad_request(transport: str = 'rest', request_type=storageinsights.DeleteReportConfigRequest): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_report_config(request) + + +def test_delete_report_config_rest_flattened(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_report_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/reportConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_report_config_rest_flattened_error(transport: str = 'rest'): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_report_config( + storageinsights.DeleteReportConfigRequest(), + name='name_value', + ) + + +def test_delete_report_config_rest_error(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + storageinsights.ListReportDetailsRequest, + dict, +]) +def test_list_report_details_rest(request_type): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/reportConfigs/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = storageinsights.ListReportDetailsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = storageinsights.ListReportDetailsResponse.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.list_report_details(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReportDetailsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_report_details_rest_required_fields(request_type=storageinsights.ListReportDetailsRequest): + transport_class = transports.StorageInsightsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + 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()).list_report_details._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_report_details._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = storageinsights.ListReportDetailsResponse() + # 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 = storageinsights.ListReportDetailsResponse.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.list_report_details(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_report_details_rest_unset_required_fields(): + transport = transports.StorageInsightsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_report_details._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_report_details_rest_interceptors(null_interceptor): + transport = transports.StorageInsightsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageInsightsRestInterceptor(), + ) + client = StorageInsightsClient(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.StorageInsightsRestInterceptor, "post_list_report_details") as post, \ + mock.patch.object(transports.StorageInsightsRestInterceptor, "pre_list_report_details") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = storageinsights.ListReportDetailsRequest.pb(storageinsights.ListReportDetailsRequest()) + 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 = storageinsights.ListReportDetailsResponse.to_json(storageinsights.ListReportDetailsResponse()) + + request = storageinsights.ListReportDetailsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = storageinsights.ListReportDetailsResponse() + + client.list_report_details(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_report_details_rest_bad_request(transport: str = 'rest', request_type=storageinsights.ListReportDetailsRequest): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/reportConfigs/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_report_details(request) + + +def test_list_report_details_rest_flattened(): + client = StorageInsightsClient( + 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 = storageinsights.ListReportDetailsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/reportConfigs/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = storageinsights.ListReportDetailsResponse.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.list_report_details(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/reportConfigs/*}/reportDetails" % client.transport._host, args[1]) + + +def test_list_report_details_rest_flattened_error(transport: str = 'rest'): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_report_details( + storageinsights.ListReportDetailsRequest(), + parent='parent_value', + ) + + +def test_list_report_details_rest_pager(transport: str = 'rest'): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + storageinsights.ListReportDetailsResponse( + report_details=[ + storageinsights.ReportDetail(), + storageinsights.ReportDetail(), + storageinsights.ReportDetail(), + ], + next_page_token='abc', + ), + storageinsights.ListReportDetailsResponse( + report_details=[], + next_page_token='def', + ), + storageinsights.ListReportDetailsResponse( + report_details=[ + storageinsights.ReportDetail(), + ], + next_page_token='ghi', + ), + storageinsights.ListReportDetailsResponse( + report_details=[ + storageinsights.ReportDetail(), + storageinsights.ReportDetail(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(storageinsights.ListReportDetailsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/reportConfigs/sample3'} + + pager = client.list_report_details(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, storageinsights.ReportDetail) + for i in results) + + pages = list(client.list_report_details(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + storageinsights.GetReportDetailRequest, + dict, +]) +def test_get_report_detail_rest(request_type): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3/reportDetails/sample4'} + 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 = storageinsights.ReportDetail( + name='name_value', + report_path_prefix='report_path_prefix_value', + shards_count=1293, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = storageinsights.ReportDetail.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_report_detail(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, storageinsights.ReportDetail) + assert response.name == 'name_value' + assert response.report_path_prefix == 'report_path_prefix_value' + assert response.shards_count == 1293 + + +def test_get_report_detail_rest_required_fields(request_type=storageinsights.GetReportDetailRequest): + transport_class = transports.StorageInsightsRestTransport + + 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_report_detail._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_report_detail._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 = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = storageinsights.ReportDetail() + # 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 = storageinsights.ReportDetail.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_report_detail(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_report_detail_rest_unset_required_fields(): + transport = transports.StorageInsightsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_report_detail._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_report_detail_rest_interceptors(null_interceptor): + transport = transports.StorageInsightsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageInsightsRestInterceptor(), + ) + client = StorageInsightsClient(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.StorageInsightsRestInterceptor, "post_get_report_detail") as post, \ + mock.patch.object(transports.StorageInsightsRestInterceptor, "pre_get_report_detail") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = storageinsights.GetReportDetailRequest.pb(storageinsights.GetReportDetailRequest()) + 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 = storageinsights.ReportDetail.to_json(storageinsights.ReportDetail()) + + request = storageinsights.GetReportDetailRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = storageinsights.ReportDetail() + + client.get_report_detail(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_report_detail_rest_bad_request(transport: str = 'rest', request_type=storageinsights.GetReportDetailRequest): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3/reportDetails/sample4'} + 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_report_detail(request) + + +def test_get_report_detail_rest_flattened(): + client = StorageInsightsClient( + 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 = storageinsights.ReportDetail() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3/reportDetails/sample4'} + + # 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 = storageinsights.ReportDetail.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_report_detail(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/reportConfigs/*/reportDetails/*}" % client.transport._host, args[1]) + + +def test_get_report_detail_rest_flattened_error(transport: str = 'rest'): + client = StorageInsightsClient( + 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_report_detail( + storageinsights.GetReportDetailRequest(), + name='name_value', + ) + + +def test_get_report_detail_rest_error(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.StorageInsightsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.StorageInsightsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StorageInsightsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.StorageInsightsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = StorageInsightsClient( + 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 = StorageInsightsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.StorageInsightsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StorageInsightsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.StorageInsightsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = StorageInsightsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.StorageInsightsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.StorageInsightsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.StorageInsightsGrpcTransport, + transports.StorageInsightsGrpcAsyncIOTransport, + transports.StorageInsightsRestTransport, +]) +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 = StorageInsightsClient.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 = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.StorageInsightsGrpcTransport, + ) + +def test_storage_insights_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.StorageInsightsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_storage_insights_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.storageinsights_v1.services.storage_insights.transports.StorageInsightsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.StorageInsightsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_report_configs', + 'get_report_config', + 'create_report_config', + 'update_report_config', + 'delete_report_config', + 'list_report_details', + 'get_report_detail', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + 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_storage_insights_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.storageinsights_v1.services.storage_insights.transports.StorageInsightsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.StorageInsightsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_storage_insights_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.storageinsights_v1.services.storage_insights.transports.StorageInsightsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.StorageInsightsTransport() + adc.assert_called_once() + + +def test_storage_insights_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) + StorageInsightsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.StorageInsightsGrpcTransport, + transports.StorageInsightsGrpcAsyncIOTransport, + ], +) +def test_storage_insights_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.StorageInsightsGrpcTransport, + transports.StorageInsightsGrpcAsyncIOTransport, + transports.StorageInsightsRestTransport, + ], +) +def test_storage_insights_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.StorageInsightsGrpcTransport, grpc_helpers), + (transports.StorageInsightsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_storage_insights_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( + "storageinsights.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="storageinsights.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.StorageInsightsGrpcTransport, transports.StorageInsightsGrpcAsyncIOTransport]) +def test_storage_insights_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_storage_insights_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.StorageInsightsRestTransport ( + 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_storage_insights_host_no_port(transport_name): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='storageinsights.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'storageinsights.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://storageinsights.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_storage_insights_host_with_port(transport_name): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='storageinsights.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'storageinsights.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://storageinsights.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_storage_insights_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = StorageInsightsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = StorageInsightsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_report_configs._session + session2 = client2.transport.list_report_configs._session + assert session1 != session2 + session1 = client1.transport.get_report_config._session + session2 = client2.transport.get_report_config._session + assert session1 != session2 + session1 = client1.transport.create_report_config._session + session2 = client2.transport.create_report_config._session + assert session1 != session2 + session1 = client1.transport.update_report_config._session + session2 = client2.transport.update_report_config._session + assert session1 != session2 + session1 = client1.transport.delete_report_config._session + session2 = client2.transport.delete_report_config._session + assert session1 != session2 + session1 = client1.transport.list_report_details._session + session2 = client2.transport.list_report_details._session + assert session1 != session2 + session1 = client1.transport.get_report_detail._session + session2 = client2.transport.get_report_detail._session + assert session1 != session2 +def test_storage_insights_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.StorageInsightsGrpcTransport( + 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_storage_insights_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.StorageInsightsGrpcAsyncIOTransport( + 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.StorageInsightsGrpcTransport, transports.StorageInsightsGrpcAsyncIOTransport]) +def test_storage_insights_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.StorageInsightsGrpcTransport, transports.StorageInsightsGrpcAsyncIOTransport]) +def test_storage_insights_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_report_config_path(): + project = "squid" + location = "clam" + report_config = "whelk" + expected = "projects/{project}/locations/{location}/reportConfigs/{report_config}".format(project=project, location=location, report_config=report_config, ) + actual = StorageInsightsClient.report_config_path(project, location, report_config) + assert expected == actual + + +def test_parse_report_config_path(): + expected = { + "project": "octopus", + "location": "oyster", + "report_config": "nudibranch", + } + path = StorageInsightsClient.report_config_path(**expected) + + # Check that the path construction is reversible. + actual = StorageInsightsClient.parse_report_config_path(path) + assert expected == actual + +def test_report_detail_path(): + project = "cuttlefish" + location = "mussel" + report_config = "winkle" + report_detail = "nautilus" + expected = "projects/{project}/locations/{location}/reportConfigs/{report_config}/reportDetails/{report_detail}".format(project=project, location=location, report_config=report_config, report_detail=report_detail, ) + actual = StorageInsightsClient.report_detail_path(project, location, report_config, report_detail) + assert expected == actual + + +def test_parse_report_detail_path(): + expected = { + "project": "scallop", + "location": "abalone", + "report_config": "squid", + "report_detail": "clam", + } + path = StorageInsightsClient.report_detail_path(**expected) + + # Check that the path construction is reversible. + actual = StorageInsightsClient.parse_report_detail_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = StorageInsightsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = StorageInsightsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = StorageInsightsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = StorageInsightsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = StorageInsightsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = StorageInsightsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = StorageInsightsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = StorageInsightsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = StorageInsightsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = StorageInsightsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = StorageInsightsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = StorageInsightsClient.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 = StorageInsightsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = StorageInsightsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = StorageInsightsClient.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.StorageInsightsTransport, '_prep_wrapped_messages') as prep: + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.StorageInsightsTransport, '_prep_wrapped_messages') as prep: + transport_class = StorageInsightsClient.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 = StorageInsightsAsyncClient( + 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_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # 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_location(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/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 = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # 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_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc"): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc"): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc"): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_field_headers(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + client = StorageInsightsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = StorageInsightsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = StorageInsightsClient( + 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 = StorageInsightsClient( + 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", [ + (StorageInsightsClient, transports.StorageInsightsGrpcTransport), + (StorageInsightsAsyncClient, transports.StorageInsightsGrpcAsyncIOTransport), +]) +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 0e281e147deb4124645cd1a5ae4507509ccb192a Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 10 Aug 2023 20:55:26 +0000 Subject: [PATCH 2/2] =?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 --- .../v1/.coveragerc | 13 - .../google-cloud-storageinsights/v1/.flake8 | 33 - .../v1/MANIFEST.in | 2 - .../v1/README.rst | 49 - .../v1/docs/conf.py | 376 - .../v1/docs/index.rst | 7 - .../v1/docs/storageinsights_v1/services.rst | 6 - .../storageinsights_v1/storage_insights.rst | 10 - .../v1/docs/storageinsights_v1/types.rst | 6 - .../google/cloud/storageinsights/__init__.py | 63 - .../cloud/storageinsights/gapic_version.py | 16 - .../v1/google/cloud/storageinsights/py.typed | 2 - .../cloud/storageinsights_v1/__init__.py | 64 - .../storageinsights_v1/gapic_metadata.json | 133 - .../cloud/storageinsights_v1/gapic_version.py | 16 - .../google/cloud/storageinsights_v1/py.typed | 2 - .../storageinsights_v1/services/__init__.py | 15 - .../services/storage_insights/__init__.py | 22 - .../services/storage_insights/async_client.py | 1277 ---- .../services/storage_insights/client.py | 1461 ---- .../services/storage_insights/pagers.py | 260 - .../storage_insights/transports/__init__.py | 38 - .../storage_insights/transports/base.py | 311 - .../storage_insights/transports/grpc.py | 532 -- .../transports/grpc_asyncio.py | 531 -- .../storage_insights/transports/rest.py | 1475 ---- .../storageinsights_v1/types/__init__.py | 56 - .../types/storageinsights.py | 764 -- .../google-cloud-storageinsights/v1/mypy.ini | 3 - .../v1/noxfile.py | 184 - ...adata_google.cloud.storageinsights.v1.json | 1152 ---- ...age_insights_create_report_config_async.py | 52 - ...rage_insights_create_report_config_sync.py | 52 - ...age_insights_delete_report_config_async.py | 50 - ...rage_insights_delete_report_config_sync.py | 50 - ...torage_insights_get_report_config_async.py | 52 - ...storage_insights_get_report_config_sync.py | 52 - ...torage_insights_get_report_detail_async.py | 52 - ...storage_insights_get_report_detail_sync.py | 52 - ...rage_insights_list_report_configs_async.py | 53 - ...orage_insights_list_report_configs_sync.py | 53 - ...rage_insights_list_report_details_async.py | 53 - ...orage_insights_list_report_details_sync.py | 53 - ...age_insights_update_report_config_async.py | 51 - ...rage_insights_update_report_config_sync.py | 51 - .../fixup_storageinsights_v1_keywords.py | 182 - .../google-cloud-storageinsights/v1/setup.py | 90 - .../v1/testing/constraints-3.10.txt | 6 - .../v1/testing/constraints-3.11.txt | 6 - .../v1/testing/constraints-3.12.txt | 6 - .../v1/testing/constraints-3.7.txt | 9 - .../v1/testing/constraints-3.8.txt | 6 - .../v1/testing/constraints-3.9.txt | 6 - .../v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/storageinsights_v1/__init__.py | 16 - .../test_storage_insights.py | 6142 ----------------- packages/google-cloud-storageinsights/.flake8 | 2 +- .../CONTRIBUTING.rst | 2 +- .../google-cloud-storageinsights/MANIFEST.in | 2 +- .../google-cloud-storageinsights/README.rst | 27 +- .../google-cloud-storageinsights/docs/conf.py | 2 +- .../services/storage_insights/async_client.py | 18 +- .../services/storage_insights/client.py | 18 +- .../storage_insights/transports/rest.py | 18 +- .../types/storageinsights.py | 3 + .../google-cloud-storageinsights/noxfile.py | 2 +- .../scripts/decrypt-secrets.sh | 2 +- 69 files changed, 59 insertions(+), 16159 deletions(-) delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/README.rst delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/services.rst delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/storage_insights.rst delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/types.rst delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/__init__.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/py.typed delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/__init__.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/async_client.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/client.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/pagers.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/types/storageinsights.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/snippet_metadata_google.cloud.storageinsights.v1.json delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_create_report_config_async.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_create_report_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_delete_report_config_async.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_delete_report_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_config_async.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_detail_async.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_detail_sync.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_details_async.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_details_sync.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_update_report_config_async.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_update_report_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/scripts/fixup_storageinsights_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/setup.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/storageinsights_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/storageinsights_v1/test_storage_insights.py diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/.coveragerc b/owl-bot-staging/google-cloud-storageinsights/v1/.coveragerc deleted file mode 100644 index f7ef2605d609..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/storageinsights/__init__.py - google/cloud/storageinsights/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/.flake8 b/owl-bot-staging/google-cloud-storageinsights/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/.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/google-cloud-storageinsights/v1/MANIFEST.in b/owl-bot-staging/google-cloud-storageinsights/v1/MANIFEST.in deleted file mode 100644 index 0d3cf11e4794..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/storageinsights *.py -recursive-include google/cloud/storageinsights_v1 *.py diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/README.rst b/owl-bot-staging/google-cloud-storageinsights/v1/README.rst deleted file mode 100644 index 92d230819bbd..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Storageinsights API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Storageinsights API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/docs/conf.py b/owl-bot-staging/google-cloud-storageinsights/v1/docs/conf.py deleted file mode 100644 index d3fa0e29914e..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-storageinsights 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-cloud-storageinsights" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-storageinsights-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-cloud-storageinsights.tex", - u"google-cloud-storageinsights 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-cloud-storageinsights", - u"Google Cloud Storageinsights 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-cloud-storageinsights", - u"google-cloud-storageinsights Documentation", - author, - "google-cloud-storageinsights", - "GAPIC library for Google Cloud Storageinsights API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/docs/index.rst b/owl-bot-staging/google-cloud-storageinsights/v1/docs/index.rst deleted file mode 100644 index 3f7f26072832..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - storageinsights_v1/services - storageinsights_v1/types diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/services.rst b/owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/services.rst deleted file mode 100644 index 7e83acde00ce..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Storageinsights v1 API -================================================ -.. toctree:: - :maxdepth: 2 - - storage_insights diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/storage_insights.rst b/owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/storage_insights.rst deleted file mode 100644 index 31171ab96163..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/storage_insights.rst +++ /dev/null @@ -1,10 +0,0 @@ -StorageInsights ---------------------------------- - -.. automodule:: google.cloud.storageinsights_v1.services.storage_insights - :members: - :inherited-members: - -.. automodule:: google.cloud.storageinsights_v1.services.storage_insights.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/types.rst b/owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/types.rst deleted file mode 100644 index 853a2bed65f9..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/docs/storageinsights_v1/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Storageinsights v1 API -============================================= - -.. automodule:: google.cloud.storageinsights_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/__init__.py deleted file mode 100644 index bcf30c8d5f34..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/__init__.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.storageinsights import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.storageinsights_v1.services.storage_insights.client import StorageInsightsClient -from google.cloud.storageinsights_v1.services.storage_insights.async_client import StorageInsightsAsyncClient - -from google.cloud.storageinsights_v1.types.storageinsights import CloudStorageDestinationOptions -from google.cloud.storageinsights_v1.types.storageinsights import CloudStorageFilters -from google.cloud.storageinsights_v1.types.storageinsights import CreateReportConfigRequest -from google.cloud.storageinsights_v1.types.storageinsights import CSVOptions -from google.cloud.storageinsights_v1.types.storageinsights import DeleteReportConfigRequest -from google.cloud.storageinsights_v1.types.storageinsights import FrequencyOptions -from google.cloud.storageinsights_v1.types.storageinsights import GetReportConfigRequest -from google.cloud.storageinsights_v1.types.storageinsights import GetReportDetailRequest -from google.cloud.storageinsights_v1.types.storageinsights import ListReportConfigsRequest -from google.cloud.storageinsights_v1.types.storageinsights import ListReportConfigsResponse -from google.cloud.storageinsights_v1.types.storageinsights import ListReportDetailsRequest -from google.cloud.storageinsights_v1.types.storageinsights import ListReportDetailsResponse -from google.cloud.storageinsights_v1.types.storageinsights import ObjectMetadataReportOptions -from google.cloud.storageinsights_v1.types.storageinsights import OperationMetadata -from google.cloud.storageinsights_v1.types.storageinsights import ParquetOptions -from google.cloud.storageinsights_v1.types.storageinsights import ReportConfig -from google.cloud.storageinsights_v1.types.storageinsights import ReportDetail -from google.cloud.storageinsights_v1.types.storageinsights import UpdateReportConfigRequest - -__all__ = ('StorageInsightsClient', - 'StorageInsightsAsyncClient', - 'CloudStorageDestinationOptions', - 'CloudStorageFilters', - 'CreateReportConfigRequest', - 'CSVOptions', - 'DeleteReportConfigRequest', - 'FrequencyOptions', - 'GetReportConfigRequest', - 'GetReportDetailRequest', - 'ListReportConfigsRequest', - 'ListReportConfigsResponse', - 'ListReportDetailsRequest', - 'ListReportDetailsResponse', - 'ObjectMetadataReportOptions', - 'OperationMetadata', - 'ParquetOptions', - 'ReportConfig', - 'ReportDetail', - 'UpdateReportConfigRequest', -) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/gapic_version.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/gapic_version.py deleted file mode 100644 index 360a0d13ebdd..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/py.typed b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/py.typed deleted file mode 100644 index 83d187acf779..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-storageinsights package uses inline types. diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/__init__.py deleted file mode 100644 index 2790a1860561..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/__init__.py +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.storageinsights_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.storage_insights import StorageInsightsClient -from .services.storage_insights import StorageInsightsAsyncClient - -from .types.storageinsights import CloudStorageDestinationOptions -from .types.storageinsights import CloudStorageFilters -from .types.storageinsights import CreateReportConfigRequest -from .types.storageinsights import CSVOptions -from .types.storageinsights import DeleteReportConfigRequest -from .types.storageinsights import FrequencyOptions -from .types.storageinsights import GetReportConfigRequest -from .types.storageinsights import GetReportDetailRequest -from .types.storageinsights import ListReportConfigsRequest -from .types.storageinsights import ListReportConfigsResponse -from .types.storageinsights import ListReportDetailsRequest -from .types.storageinsights import ListReportDetailsResponse -from .types.storageinsights import ObjectMetadataReportOptions -from .types.storageinsights import OperationMetadata -from .types.storageinsights import ParquetOptions -from .types.storageinsights import ReportConfig -from .types.storageinsights import ReportDetail -from .types.storageinsights import UpdateReportConfigRequest - -__all__ = ( - 'StorageInsightsAsyncClient', -'CSVOptions', -'CloudStorageDestinationOptions', -'CloudStorageFilters', -'CreateReportConfigRequest', -'DeleteReportConfigRequest', -'FrequencyOptions', -'GetReportConfigRequest', -'GetReportDetailRequest', -'ListReportConfigsRequest', -'ListReportConfigsResponse', -'ListReportDetailsRequest', -'ListReportDetailsResponse', -'ObjectMetadataReportOptions', -'OperationMetadata', -'ParquetOptions', -'ReportConfig', -'ReportDetail', -'StorageInsightsClient', -'UpdateReportConfigRequest', -) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/gapic_metadata.json deleted file mode 100644 index 1456239dafb4..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/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.cloud.storageinsights_v1", - "protoPackage": "google.cloud.storageinsights.v1", - "schema": "1.0", - "services": { - "StorageInsights": { - "clients": { - "grpc": { - "libraryClient": "StorageInsightsClient", - "rpcs": { - "CreateReportConfig": { - "methods": [ - "create_report_config" - ] - }, - "DeleteReportConfig": { - "methods": [ - "delete_report_config" - ] - }, - "GetReportConfig": { - "methods": [ - "get_report_config" - ] - }, - "GetReportDetail": { - "methods": [ - "get_report_detail" - ] - }, - "ListReportConfigs": { - "methods": [ - "list_report_configs" - ] - }, - "ListReportDetails": { - "methods": [ - "list_report_details" - ] - }, - "UpdateReportConfig": { - "methods": [ - "update_report_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "StorageInsightsAsyncClient", - "rpcs": { - "CreateReportConfig": { - "methods": [ - "create_report_config" - ] - }, - "DeleteReportConfig": { - "methods": [ - "delete_report_config" - ] - }, - "GetReportConfig": { - "methods": [ - "get_report_config" - ] - }, - "GetReportDetail": { - "methods": [ - "get_report_detail" - ] - }, - "ListReportConfigs": { - "methods": [ - "list_report_configs" - ] - }, - "ListReportDetails": { - "methods": [ - "list_report_details" - ] - }, - "UpdateReportConfig": { - "methods": [ - "update_report_config" - ] - } - } - }, - "rest": { - "libraryClient": "StorageInsightsClient", - "rpcs": { - "CreateReportConfig": { - "methods": [ - "create_report_config" - ] - }, - "DeleteReportConfig": { - "methods": [ - "delete_report_config" - ] - }, - "GetReportConfig": { - "methods": [ - "get_report_config" - ] - }, - "GetReportDetail": { - "methods": [ - "get_report_detail" - ] - }, - "ListReportConfigs": { - "methods": [ - "list_report_configs" - ] - }, - "ListReportDetails": { - "methods": [ - "list_report_details" - ] - }, - "UpdateReportConfig": { - "methods": [ - "update_report_config" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/gapic_version.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/gapic_version.py deleted file mode 100644 index 360a0d13ebdd..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/py.typed b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/py.typed deleted file mode 100644 index 83d187acf779..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-storageinsights package uses inline types. diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/__init__.py deleted file mode 100644 index 89a37dc92c5a..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/__init__.py deleted file mode 100644 index 92168b4a07a4..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 StorageInsightsClient -from .async_client import StorageInsightsAsyncClient - -__all__ = ( - 'StorageInsightsClient', - 'StorageInsightsAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/async_client.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/async_client.py deleted file mode 100644 index 9063010ccd29..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/async_client.py +++ /dev/null @@ -1,1277 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.storageinsights_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.storageinsights_v1.services.storage_insights import pagers -from google.cloud.storageinsights_v1.types import storageinsights -from google.longrunning import operations_pb2 -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import datetime_pb2 # type: ignore -from .transports.base import StorageInsightsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import StorageInsightsGrpcAsyncIOTransport -from .client import StorageInsightsClient - - -class StorageInsightsAsyncClient: - """Service describing handlers for resources""" - - _client: StorageInsightsClient - - DEFAULT_ENDPOINT = StorageInsightsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = StorageInsightsClient.DEFAULT_MTLS_ENDPOINT - - report_config_path = staticmethod(StorageInsightsClient.report_config_path) - parse_report_config_path = staticmethod(StorageInsightsClient.parse_report_config_path) - report_detail_path = staticmethod(StorageInsightsClient.report_detail_path) - parse_report_detail_path = staticmethod(StorageInsightsClient.parse_report_detail_path) - common_billing_account_path = staticmethod(StorageInsightsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(StorageInsightsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(StorageInsightsClient.common_folder_path) - parse_common_folder_path = staticmethod(StorageInsightsClient.parse_common_folder_path) - common_organization_path = staticmethod(StorageInsightsClient.common_organization_path) - parse_common_organization_path = staticmethod(StorageInsightsClient.parse_common_organization_path) - common_project_path = staticmethod(StorageInsightsClient.common_project_path) - parse_common_project_path = staticmethod(StorageInsightsClient.parse_common_project_path) - common_location_path = staticmethod(StorageInsightsClient.common_location_path) - parse_common_location_path = staticmethod(StorageInsightsClient.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: - StorageInsightsAsyncClient: The constructed client. - """ - return StorageInsightsClient.from_service_account_info.__func__(StorageInsightsAsyncClient, 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: - StorageInsightsAsyncClient: The constructed client. - """ - return StorageInsightsClient.from_service_account_file.__func__(StorageInsightsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return StorageInsightsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> StorageInsightsTransport: - """Returns the transport used by the client instance. - - Returns: - StorageInsightsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(StorageInsightsClient).get_transport_class, type(StorageInsightsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, StorageInsightsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the storage insights 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, ~.StorageInsightsTransport]): 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 = StorageInsightsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_report_configs(self, - request: Optional[Union[storageinsights.ListReportConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListReportConfigsAsyncPager: - r"""Lists ReportConfigs in a given project and location. - - .. 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.cloud import storageinsights_v1 - - async def sample_list_report_configs(): - # Create a client - client = storageinsights_v1.StorageInsightsAsyncClient() - - # Initialize request argument(s) - request = storageinsights_v1.ListReportConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_report_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.storageinsights_v1.types.ListReportConfigsRequest, dict]]): - The request object. Message for requesting list of - ReportConfigs - parent (:class:`str`): - Required. Parent value for - ListReportConfigsRequest - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.storageinsights_v1.services.storage_insights.pagers.ListReportConfigsAsyncPager: - Message for response to listing - ReportConfigs - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = storageinsights.ListReportConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_report_configs, - default_retry=retries.Retry( -initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - 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(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListReportConfigsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_report_config(self, - request: Optional[Union[storageinsights.GetReportConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> storageinsights.ReportConfig: - r"""Gets details of a single ReportConfig. - - .. 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.cloud import storageinsights_v1 - - async def sample_get_report_config(): - # Create a client - client = storageinsights_v1.StorageInsightsAsyncClient() - - # Initialize request argument(s) - request = storageinsights_v1.GetReportConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_report_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.storageinsights_v1.types.GetReportConfigRequest, dict]]): - The request object. Message for getting a ReportConfig - name (:class:`str`): - Required. Name of the resource - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.storageinsights_v1.types.ReportConfig: - Message describing ReportConfig - object. ReportConfig is the - configuration to generate reports. See - https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest - for more details on how to set various - fields. Next ID: 12 - - """ - # Create or coerce a protobuf request object. - # Quick check: 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 = storageinsights.GetReportConfigRequest(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_report_config, - default_retry=retries.Retry( -initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - 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 create_report_config(self, - request: Optional[Union[storageinsights.CreateReportConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - report_config: Optional[storageinsights.ReportConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> storageinsights.ReportConfig: - r"""Creates a new ReportConfig in a given project and - location. - - .. 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.cloud import storageinsights_v1 - - async def sample_create_report_config(): - # Create a client - client = storageinsights_v1.StorageInsightsAsyncClient() - - # Initialize request argument(s) - request = storageinsights_v1.CreateReportConfigRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_report_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.storageinsights_v1.types.CreateReportConfigRequest, dict]]): - The request object. Message for creating a ReportConfig - parent (:class:`str`): - Required. Value for parent. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - report_config (:class:`google.cloud.storageinsights_v1.types.ReportConfig`): - Required. The resource being created - This corresponds to the ``report_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.storageinsights_v1.types.ReportConfig: - Message describing ReportConfig - object. ReportConfig is the - configuration to generate reports. See - https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest - for more details on how to set various - fields. Next ID: 12 - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, report_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = storageinsights.CreateReportConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if report_config is not None: - request.report_config = report_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_report_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_report_config(self, - request: Optional[Union[storageinsights.UpdateReportConfigRequest, dict]] = None, - *, - report_config: Optional[storageinsights.ReportConfig] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> storageinsights.ReportConfig: - r"""Updates the parameters of a single ReportConfig. - - .. 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.cloud import storageinsights_v1 - - async def sample_update_report_config(): - # Create a client - client = storageinsights_v1.StorageInsightsAsyncClient() - - # Initialize request argument(s) - request = storageinsights_v1.UpdateReportConfigRequest( - ) - - # Make the request - response = await client.update_report_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.storageinsights_v1.types.UpdateReportConfigRequest, dict]]): - The request object. Message for updating a ReportConfig - report_config (:class:`google.cloud.storageinsights_v1.types.ReportConfig`): - Required. The resource being updated - This corresponds to the ``report_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Field mask is used to specify the fields to be - overwritten in the ReportConfig resource by the update. - The fields specified in the update_mask are relative to - the resource, not the full request. A field will be - overwritten if it is in the mask. If the user does not - provide a mask then all fields will be overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.storageinsights_v1.types.ReportConfig: - Message describing ReportConfig - object. ReportConfig is the - configuration to generate reports. See - https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest - for more details on how to set various - fields. Next ID: 12 - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([report_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = storageinsights.UpdateReportConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if report_config is not None: - request.report_config = report_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_report_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("report_config.name", request.report_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_report_config(self, - request: Optional[Union[storageinsights.DeleteReportConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a single ReportConfig. - - .. 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.cloud import storageinsights_v1 - - async def sample_delete_report_config(): - # Create a client - client = storageinsights_v1.StorageInsightsAsyncClient() - - # Initialize request argument(s) - request = storageinsights_v1.DeleteReportConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_report_config(request=request) - - Args: - request (Optional[Union[google.cloud.storageinsights_v1.types.DeleteReportConfigRequest, dict]]): - The request object. Message for deleting a ReportConfig - name (:class:`str`): - Required. Name of the resource - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = storageinsights.DeleteReportConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_report_config, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def list_report_details(self, - request: Optional[Union[storageinsights.ListReportDetailsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListReportDetailsAsyncPager: - r"""Lists ReportDetails in a given project and location. - - .. 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.cloud import storageinsights_v1 - - async def sample_list_report_details(): - # Create a client - client = storageinsights_v1.StorageInsightsAsyncClient() - - # Initialize request argument(s) - request = storageinsights_v1.ListReportDetailsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_report_details(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.storageinsights_v1.types.ListReportDetailsRequest, dict]]): - The request object. Message for requesting list of - ReportDetails - parent (:class:`str`): - Required. Parent value for - ListReportDetailsRequest - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.storageinsights_v1.services.storage_insights.pagers.ListReportDetailsAsyncPager: - Message for response to listing - ReportDetails - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = storageinsights.ListReportDetailsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_report_details, - default_retry=retries.Retry( -initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - 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(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListReportDetailsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_report_detail(self, - request: Optional[Union[storageinsights.GetReportDetailRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> storageinsights.ReportDetail: - r"""Gets details of a single ReportDetail. - - .. 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.cloud import storageinsights_v1 - - async def sample_get_report_detail(): - # Create a client - client = storageinsights_v1.StorageInsightsAsyncClient() - - # Initialize request argument(s) - request = storageinsights_v1.GetReportDetailRequest( - name="name_value", - ) - - # Make the request - response = await client.get_report_detail(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.storageinsights_v1.types.GetReportDetailRequest, dict]]): - The request object. Message for getting a ReportDetail - name (:class:`str`): - Required. Name of the resource - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.storageinsights_v1.types.ReportDetail: - Message describing ReportDetail - object. ReportDetail represents metadata - of generated reports for a ReportConfig. - Next ID: 10 - - """ - # Create or coerce a protobuf request object. - # Quick check: 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 = storageinsights.GetReportDetailRequest(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_report_detail, - default_retry=retries.Retry( -initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - 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 list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "StorageInsightsAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "StorageInsightsAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/client.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/client.py deleted file mode 100644 index d51b46ab2e31..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/client.py +++ /dev/null @@ -1,1461 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -from google.cloud.storageinsights_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.storageinsights_v1.services.storage_insights import pagers -from google.cloud.storageinsights_v1.types import storageinsights -from google.longrunning import operations_pb2 -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import datetime_pb2 # type: ignore -from .transports.base import StorageInsightsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import StorageInsightsGrpcTransport -from .transports.grpc_asyncio import StorageInsightsGrpcAsyncIOTransport -from .transports.rest import StorageInsightsRestTransport - - -class StorageInsightsClientMeta(type): - """Metaclass for the StorageInsights 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[StorageInsightsTransport]] - _transport_registry["grpc"] = StorageInsightsGrpcTransport - _transport_registry["grpc_asyncio"] = StorageInsightsGrpcAsyncIOTransport - _transport_registry["rest"] = StorageInsightsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[StorageInsightsTransport]: - """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 StorageInsightsClient(metaclass=StorageInsightsClientMeta): - """Service describing handlers for resources""" - - @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 = "storageinsights.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: - StorageInsightsClient: 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: - StorageInsightsClient: 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) -> StorageInsightsTransport: - """Returns the transport used by the client instance. - - Returns: - StorageInsightsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def report_config_path(project: str,location: str,report_config: str,) -> str: - """Returns a fully-qualified report_config string.""" - return "projects/{project}/locations/{location}/reportConfigs/{report_config}".format(project=project, location=location, report_config=report_config, ) - - @staticmethod - def parse_report_config_path(path: str) -> Dict[str,str]: - """Parses a report_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/reportConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def report_detail_path(project: str,location: str,report_config: str,report_detail: str,) -> str: - """Returns a fully-qualified report_detail string.""" - return "projects/{project}/locations/{location}/reportConfigs/{report_config}/reportDetails/{report_detail}".format(project=project, location=location, report_config=report_config, report_detail=report_detail, ) - - @staticmethod - def parse_report_detail_path(path: str) -> Dict[str,str]: - """Parses a report_detail path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/reportConfigs/(?P.+?)/reportDetails/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - 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, StorageInsightsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the storage insights 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, StorageInsightsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. 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, StorageInsightsTransport): - # transport is a StorageInsightsTransport 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 list_report_configs(self, - request: Optional[Union[storageinsights.ListReportConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListReportConfigsPager: - r"""Lists ReportConfigs in a given project and location. - - .. 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.cloud import storageinsights_v1 - - def sample_list_report_configs(): - # Create a client - client = storageinsights_v1.StorageInsightsClient() - - # Initialize request argument(s) - request = storageinsights_v1.ListReportConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_report_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.storageinsights_v1.types.ListReportConfigsRequest, dict]): - The request object. Message for requesting list of - ReportConfigs - parent (str): - Required. Parent value for - ListReportConfigsRequest - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.storageinsights_v1.services.storage_insights.pagers.ListReportConfigsPager: - Message for response to listing - ReportConfigs - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a storageinsights.ListReportConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, storageinsights.ListReportConfigsRequest): - request = storageinsights.ListReportConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_report_configs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListReportConfigsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_report_config(self, - request: Optional[Union[storageinsights.GetReportConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> storageinsights.ReportConfig: - r"""Gets details of a single ReportConfig. - - .. 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.cloud import storageinsights_v1 - - def sample_get_report_config(): - # Create a client - client = storageinsights_v1.StorageInsightsClient() - - # Initialize request argument(s) - request = storageinsights_v1.GetReportConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_report_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.storageinsights_v1.types.GetReportConfigRequest, dict]): - The request object. Message for getting a ReportConfig - name (str): - Required. Name of the resource - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.storageinsights_v1.types.ReportConfig: - Message describing ReportConfig - object. ReportConfig is the - configuration to generate reports. See - https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest - for more details on how to set various - fields. Next ID: 12 - - """ - # Create or coerce a protobuf request object. - # Quick check: 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 storageinsights.GetReportConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, storageinsights.GetReportConfigRequest): - request = storageinsights.GetReportConfigRequest(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_report_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_report_config(self, - request: Optional[Union[storageinsights.CreateReportConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - report_config: Optional[storageinsights.ReportConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> storageinsights.ReportConfig: - r"""Creates a new ReportConfig in a given project and - location. - - .. 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.cloud import storageinsights_v1 - - def sample_create_report_config(): - # Create a client - client = storageinsights_v1.StorageInsightsClient() - - # Initialize request argument(s) - request = storageinsights_v1.CreateReportConfigRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_report_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.storageinsights_v1.types.CreateReportConfigRequest, dict]): - The request object. Message for creating a ReportConfig - parent (str): - Required. Value for parent. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - report_config (google.cloud.storageinsights_v1.types.ReportConfig): - Required. The resource being created - This corresponds to the ``report_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.storageinsights_v1.types.ReportConfig: - Message describing ReportConfig - object. ReportConfig is the - configuration to generate reports. See - https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest - for more details on how to set various - fields. Next ID: 12 - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, report_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a storageinsights.CreateReportConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, storageinsights.CreateReportConfigRequest): - request = storageinsights.CreateReportConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if report_config is not None: - request.report_config = report_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_report_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_report_config(self, - request: Optional[Union[storageinsights.UpdateReportConfigRequest, dict]] = None, - *, - report_config: Optional[storageinsights.ReportConfig] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> storageinsights.ReportConfig: - r"""Updates the parameters of a single ReportConfig. - - .. 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.cloud import storageinsights_v1 - - def sample_update_report_config(): - # Create a client - client = storageinsights_v1.StorageInsightsClient() - - # Initialize request argument(s) - request = storageinsights_v1.UpdateReportConfigRequest( - ) - - # Make the request - response = client.update_report_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.storageinsights_v1.types.UpdateReportConfigRequest, dict]): - The request object. Message for updating a ReportConfig - report_config (google.cloud.storageinsights_v1.types.ReportConfig): - Required. The resource being updated - This corresponds to the ``report_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Field mask is used to specify the fields to be - overwritten in the ReportConfig resource by the update. - The fields specified in the update_mask are relative to - the resource, not the full request. A field will be - overwritten if it is in the mask. If the user does not - provide a mask then all fields will be overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.storageinsights_v1.types.ReportConfig: - Message describing ReportConfig - object. ReportConfig is the - configuration to generate reports. See - https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest - for more details on how to set various - fields. Next ID: 12 - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([report_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a storageinsights.UpdateReportConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, storageinsights.UpdateReportConfigRequest): - request = storageinsights.UpdateReportConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if report_config is not None: - request.report_config = report_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_report_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("report_config.name", request.report_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_report_config(self, - request: Optional[Union[storageinsights.DeleteReportConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a single ReportConfig. - - .. 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.cloud import storageinsights_v1 - - def sample_delete_report_config(): - # Create a client - client = storageinsights_v1.StorageInsightsClient() - - # Initialize request argument(s) - request = storageinsights_v1.DeleteReportConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_report_config(request=request) - - Args: - request (Union[google.cloud.storageinsights_v1.types.DeleteReportConfigRequest, dict]): - The request object. Message for deleting a ReportConfig - name (str): - Required. Name of the resource - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a storageinsights.DeleteReportConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, storageinsights.DeleteReportConfigRequest): - request = storageinsights.DeleteReportConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_report_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def list_report_details(self, - request: Optional[Union[storageinsights.ListReportDetailsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListReportDetailsPager: - r"""Lists ReportDetails in a given project and location. - - .. 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.cloud import storageinsights_v1 - - def sample_list_report_details(): - # Create a client - client = storageinsights_v1.StorageInsightsClient() - - # Initialize request argument(s) - request = storageinsights_v1.ListReportDetailsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_report_details(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.storageinsights_v1.types.ListReportDetailsRequest, dict]): - The request object. Message for requesting list of - ReportDetails - parent (str): - Required. Parent value for - ListReportDetailsRequest - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.storageinsights_v1.services.storage_insights.pagers.ListReportDetailsPager: - Message for response to listing - ReportDetails - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a storageinsights.ListReportDetailsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, storageinsights.ListReportDetailsRequest): - request = storageinsights.ListReportDetailsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_report_details] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListReportDetailsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_report_detail(self, - request: Optional[Union[storageinsights.GetReportDetailRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> storageinsights.ReportDetail: - r"""Gets details of a single ReportDetail. - - .. 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.cloud import storageinsights_v1 - - def sample_get_report_detail(): - # Create a client - client = storageinsights_v1.StorageInsightsClient() - - # Initialize request argument(s) - request = storageinsights_v1.GetReportDetailRequest( - name="name_value", - ) - - # Make the request - response = client.get_report_detail(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.storageinsights_v1.types.GetReportDetailRequest, dict]): - The request object. Message for getting a ReportDetail - name (str): - Required. Name of the resource - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.storageinsights_v1.types.ReportDetail: - Message describing ReportDetail - object. ReportDetail represents metadata - of generated reports for a ReportConfig. - Next ID: 10 - - """ - # Create or coerce a protobuf request object. - # Quick check: 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 storageinsights.GetReportDetailRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, storageinsights.GetReportDetailRequest): - request = storageinsights.GetReportDetailRequest(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_report_detail] - - # Certain 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 __enter__(self) -> "StorageInsightsClient": - 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() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "StorageInsightsClient", -) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/pagers.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/pagers.py deleted file mode 100644 index 8b990938faa0..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/pagers.py +++ /dev/null @@ -1,260 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.storageinsights_v1.types import storageinsights - - -class ListReportConfigsPager: - """A pager for iterating through ``list_report_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.storageinsights_v1.types.ListReportConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``report_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListReportConfigs`` requests and continue to iterate - through the ``report_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.storageinsights_v1.types.ListReportConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., storageinsights.ListReportConfigsResponse], - request: storageinsights.ListReportConfigsRequest, - response: storageinsights.ListReportConfigsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.storageinsights_v1.types.ListReportConfigsRequest): - The initial request object. - response (google.cloud.storageinsights_v1.types.ListReportConfigsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = storageinsights.ListReportConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[storageinsights.ListReportConfigsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[storageinsights.ReportConfig]: - for page in self.pages: - yield from page.report_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListReportConfigsAsyncPager: - """A pager for iterating through ``list_report_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.storageinsights_v1.types.ListReportConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``report_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListReportConfigs`` requests and continue to iterate - through the ``report_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.storageinsights_v1.types.ListReportConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[storageinsights.ListReportConfigsResponse]], - request: storageinsights.ListReportConfigsRequest, - response: storageinsights.ListReportConfigsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.storageinsights_v1.types.ListReportConfigsRequest): - The initial request object. - response (google.cloud.storageinsights_v1.types.ListReportConfigsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = storageinsights.ListReportConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[storageinsights.ListReportConfigsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[storageinsights.ReportConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.report_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListReportDetailsPager: - """A pager for iterating through ``list_report_details`` requests. - - This class thinly wraps an initial - :class:`google.cloud.storageinsights_v1.types.ListReportDetailsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``report_details`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListReportDetails`` requests and continue to iterate - through the ``report_details`` field on the - corresponding responses. - - All the usual :class:`google.cloud.storageinsights_v1.types.ListReportDetailsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., storageinsights.ListReportDetailsResponse], - request: storageinsights.ListReportDetailsRequest, - response: storageinsights.ListReportDetailsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.storageinsights_v1.types.ListReportDetailsRequest): - The initial request object. - response (google.cloud.storageinsights_v1.types.ListReportDetailsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = storageinsights.ListReportDetailsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[storageinsights.ListReportDetailsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[storageinsights.ReportDetail]: - for page in self.pages: - yield from page.report_details - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListReportDetailsAsyncPager: - """A pager for iterating through ``list_report_details`` requests. - - This class thinly wraps an initial - :class:`google.cloud.storageinsights_v1.types.ListReportDetailsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``report_details`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListReportDetails`` requests and continue to iterate - through the ``report_details`` field on the - corresponding responses. - - All the usual :class:`google.cloud.storageinsights_v1.types.ListReportDetailsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[storageinsights.ListReportDetailsResponse]], - request: storageinsights.ListReportDetailsRequest, - response: storageinsights.ListReportDetailsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.storageinsights_v1.types.ListReportDetailsRequest): - The initial request object. - response (google.cloud.storageinsights_v1.types.ListReportDetailsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = storageinsights.ListReportDetailsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[storageinsights.ListReportDetailsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[storageinsights.ReportDetail]: - async def async_generator(): - async for page in self.pages: - for response in page.report_details: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/__init__.py deleted file mode 100644 index 582c4e3c6534..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 StorageInsightsTransport -from .grpc import StorageInsightsGrpcTransport -from .grpc_asyncio import StorageInsightsGrpcAsyncIOTransport -from .rest import StorageInsightsRestTransport -from .rest import StorageInsightsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[StorageInsightsTransport]] -_transport_registry['grpc'] = StorageInsightsGrpcTransport -_transport_registry['grpc_asyncio'] = StorageInsightsGrpcAsyncIOTransport -_transport_registry['rest'] = StorageInsightsRestTransport - -__all__ = ( - 'StorageInsightsTransport', - 'StorageInsightsGrpcTransport', - 'StorageInsightsGrpcAsyncIOTransport', - 'StorageInsightsRestTransport', - 'StorageInsightsRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/base.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/base.py deleted file mode 100644 index 0abd0f1aa732..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/base.py +++ /dev/null @@ -1,311 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.storageinsights_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.storageinsights_v1.types import storageinsights -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class StorageInsightsTransport(abc.ABC): - """Abstract transport class for StorageInsights.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'storageinsights.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.list_report_configs: gapic_v1.method.wrap_method( - self.list_report_configs, - default_retry=retries.Retry( -initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_report_config: gapic_v1.method.wrap_method( - self.get_report_config, - default_retry=retries.Retry( -initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_report_config: gapic_v1.method.wrap_method( - self.create_report_config, - default_timeout=None, - client_info=client_info, - ), - self.update_report_config: gapic_v1.method.wrap_method( - self.update_report_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_report_config: gapic_v1.method.wrap_method( - self.delete_report_config, - default_timeout=None, - client_info=client_info, - ), - self.list_report_details: gapic_v1.method.wrap_method( - self.list_report_details, - default_retry=retries.Retry( -initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_report_detail: gapic_v1.method.wrap_method( - self.get_report_detail, - default_retry=retries.Retry( -initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - 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 list_report_configs(self) -> Callable[ - [storageinsights.ListReportConfigsRequest], - Union[ - storageinsights.ListReportConfigsResponse, - Awaitable[storageinsights.ListReportConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def get_report_config(self) -> Callable[ - [storageinsights.GetReportConfigRequest], - Union[ - storageinsights.ReportConfig, - Awaitable[storageinsights.ReportConfig] - ]]: - raise NotImplementedError() - - @property - def create_report_config(self) -> Callable[ - [storageinsights.CreateReportConfigRequest], - Union[ - storageinsights.ReportConfig, - Awaitable[storageinsights.ReportConfig] - ]]: - raise NotImplementedError() - - @property - def update_report_config(self) -> Callable[ - [storageinsights.UpdateReportConfigRequest], - Union[ - storageinsights.ReportConfig, - Awaitable[storageinsights.ReportConfig] - ]]: - raise NotImplementedError() - - @property - def delete_report_config(self) -> Callable[ - [storageinsights.DeleteReportConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_report_details(self) -> Callable[ - [storageinsights.ListReportDetailsRequest], - Union[ - storageinsights.ListReportDetailsResponse, - Awaitable[storageinsights.ListReportDetailsResponse] - ]]: - raise NotImplementedError() - - @property - def get_report_detail(self) -> Callable[ - [storageinsights.GetReportDetailRequest], - Union[ - storageinsights.ReportDetail, - Awaitable[storageinsights.ReportDetail] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def delete_operation( - self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'StorageInsightsTransport', -) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/grpc.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/grpc.py deleted file mode 100644 index 1007801a31d8..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/grpc.py +++ /dev/null @@ -1,532 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.storageinsights_v1.types import storageinsights -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from .base import StorageInsightsTransport, DEFAULT_CLIENT_INFO - - -class StorageInsightsGrpcTransport(StorageInsightsTransport): - """gRPC backend transport for StorageInsights. - - Service describing handlers for resources - - 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 = 'storageinsights.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 = 'storageinsights.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 list_report_configs(self) -> Callable[ - [storageinsights.ListReportConfigsRequest], - storageinsights.ListReportConfigsResponse]: - r"""Return a callable for the list report configs method over gRPC. - - Lists ReportConfigs in a given project and location. - - Returns: - Callable[[~.ListReportConfigsRequest], - ~.ListReportConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_report_configs' not in self._stubs: - self._stubs['list_report_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.storageinsights.v1.StorageInsights/ListReportConfigs', - request_serializer=storageinsights.ListReportConfigsRequest.serialize, - response_deserializer=storageinsights.ListReportConfigsResponse.deserialize, - ) - return self._stubs['list_report_configs'] - - @property - def get_report_config(self) -> Callable[ - [storageinsights.GetReportConfigRequest], - storageinsights.ReportConfig]: - r"""Return a callable for the get report config method over gRPC. - - Gets details of a single ReportConfig. - - Returns: - Callable[[~.GetReportConfigRequest], - ~.ReportConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_report_config' not in self._stubs: - self._stubs['get_report_config'] = self.grpc_channel.unary_unary( - '/google.cloud.storageinsights.v1.StorageInsights/GetReportConfig', - request_serializer=storageinsights.GetReportConfigRequest.serialize, - response_deserializer=storageinsights.ReportConfig.deserialize, - ) - return self._stubs['get_report_config'] - - @property - def create_report_config(self) -> Callable[ - [storageinsights.CreateReportConfigRequest], - storageinsights.ReportConfig]: - r"""Return a callable for the create report config method over gRPC. - - Creates a new ReportConfig in a given project and - location. - - Returns: - Callable[[~.CreateReportConfigRequest], - ~.ReportConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_report_config' not in self._stubs: - self._stubs['create_report_config'] = self.grpc_channel.unary_unary( - '/google.cloud.storageinsights.v1.StorageInsights/CreateReportConfig', - request_serializer=storageinsights.CreateReportConfigRequest.serialize, - response_deserializer=storageinsights.ReportConfig.deserialize, - ) - return self._stubs['create_report_config'] - - @property - def update_report_config(self) -> Callable[ - [storageinsights.UpdateReportConfigRequest], - storageinsights.ReportConfig]: - r"""Return a callable for the update report config method over gRPC. - - Updates the parameters of a single ReportConfig. - - Returns: - Callable[[~.UpdateReportConfigRequest], - ~.ReportConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_report_config' not in self._stubs: - self._stubs['update_report_config'] = self.grpc_channel.unary_unary( - '/google.cloud.storageinsights.v1.StorageInsights/UpdateReportConfig', - request_serializer=storageinsights.UpdateReportConfigRequest.serialize, - response_deserializer=storageinsights.ReportConfig.deserialize, - ) - return self._stubs['update_report_config'] - - @property - def delete_report_config(self) -> Callable[ - [storageinsights.DeleteReportConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete report config method over gRPC. - - Deletes a single ReportConfig. - - Returns: - Callable[[~.DeleteReportConfigRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_report_config' not in self._stubs: - self._stubs['delete_report_config'] = self.grpc_channel.unary_unary( - '/google.cloud.storageinsights.v1.StorageInsights/DeleteReportConfig', - request_serializer=storageinsights.DeleteReportConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_report_config'] - - @property - def list_report_details(self) -> Callable[ - [storageinsights.ListReportDetailsRequest], - storageinsights.ListReportDetailsResponse]: - r"""Return a callable for the list report details method over gRPC. - - Lists ReportDetails in a given project and location. - - Returns: - Callable[[~.ListReportDetailsRequest], - ~.ListReportDetailsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_report_details' not in self._stubs: - self._stubs['list_report_details'] = self.grpc_channel.unary_unary( - '/google.cloud.storageinsights.v1.StorageInsights/ListReportDetails', - request_serializer=storageinsights.ListReportDetailsRequest.serialize, - response_deserializer=storageinsights.ListReportDetailsResponse.deserialize, - ) - return self._stubs['list_report_details'] - - @property - def get_report_detail(self) -> Callable[ - [storageinsights.GetReportDetailRequest], - storageinsights.ReportDetail]: - r"""Return a callable for the get report detail method over gRPC. - - Gets details of a single ReportDetail. - - Returns: - Callable[[~.GetReportDetailRequest], - ~.ReportDetail]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_report_detail' not in self._stubs: - self._stubs['get_report_detail'] = self.grpc_channel.unary_unary( - '/google.cloud.storageinsights.v1.StorageInsights/GetReportDetail', - request_serializer=storageinsights.GetReportDetailRequest.serialize, - response_deserializer=storageinsights.ReportDetail.deserialize, - ) - return self._stubs['get_report_detail'] - - def close(self): - self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'StorageInsightsGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/grpc_asyncio.py deleted file mode 100644 index 8a8ecfa59d3f..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/grpc_asyncio.py +++ /dev/null @@ -1,531 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.storageinsights_v1.types import storageinsights -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from .base import StorageInsightsTransport, DEFAULT_CLIENT_INFO -from .grpc import StorageInsightsGrpcTransport - - -class StorageInsightsGrpcAsyncIOTransport(StorageInsightsTransport): - """gRPC AsyncIO backend transport for StorageInsights. - - Service describing handlers for resources - - 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 = 'storageinsights.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 = 'storageinsights.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 list_report_configs(self) -> Callable[ - [storageinsights.ListReportConfigsRequest], - Awaitable[storageinsights.ListReportConfigsResponse]]: - r"""Return a callable for the list report configs method over gRPC. - - Lists ReportConfigs in a given project and location. - - Returns: - Callable[[~.ListReportConfigsRequest], - Awaitable[~.ListReportConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_report_configs' not in self._stubs: - self._stubs['list_report_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.storageinsights.v1.StorageInsights/ListReportConfigs', - request_serializer=storageinsights.ListReportConfigsRequest.serialize, - response_deserializer=storageinsights.ListReportConfigsResponse.deserialize, - ) - return self._stubs['list_report_configs'] - - @property - def get_report_config(self) -> Callable[ - [storageinsights.GetReportConfigRequest], - Awaitable[storageinsights.ReportConfig]]: - r"""Return a callable for the get report config method over gRPC. - - Gets details of a single ReportConfig. - - Returns: - Callable[[~.GetReportConfigRequest], - Awaitable[~.ReportConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_report_config' not in self._stubs: - self._stubs['get_report_config'] = self.grpc_channel.unary_unary( - '/google.cloud.storageinsights.v1.StorageInsights/GetReportConfig', - request_serializer=storageinsights.GetReportConfigRequest.serialize, - response_deserializer=storageinsights.ReportConfig.deserialize, - ) - return self._stubs['get_report_config'] - - @property - def create_report_config(self) -> Callable[ - [storageinsights.CreateReportConfigRequest], - Awaitable[storageinsights.ReportConfig]]: - r"""Return a callable for the create report config method over gRPC. - - Creates a new ReportConfig in a given project and - location. - - Returns: - Callable[[~.CreateReportConfigRequest], - Awaitable[~.ReportConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_report_config' not in self._stubs: - self._stubs['create_report_config'] = self.grpc_channel.unary_unary( - '/google.cloud.storageinsights.v1.StorageInsights/CreateReportConfig', - request_serializer=storageinsights.CreateReportConfigRequest.serialize, - response_deserializer=storageinsights.ReportConfig.deserialize, - ) - return self._stubs['create_report_config'] - - @property - def update_report_config(self) -> Callable[ - [storageinsights.UpdateReportConfigRequest], - Awaitable[storageinsights.ReportConfig]]: - r"""Return a callable for the update report config method over gRPC. - - Updates the parameters of a single ReportConfig. - - Returns: - Callable[[~.UpdateReportConfigRequest], - Awaitable[~.ReportConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_report_config' not in self._stubs: - self._stubs['update_report_config'] = self.grpc_channel.unary_unary( - '/google.cloud.storageinsights.v1.StorageInsights/UpdateReportConfig', - request_serializer=storageinsights.UpdateReportConfigRequest.serialize, - response_deserializer=storageinsights.ReportConfig.deserialize, - ) - return self._stubs['update_report_config'] - - @property - def delete_report_config(self) -> Callable[ - [storageinsights.DeleteReportConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete report config method over gRPC. - - Deletes a single ReportConfig. - - Returns: - Callable[[~.DeleteReportConfigRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_report_config' not in self._stubs: - self._stubs['delete_report_config'] = self.grpc_channel.unary_unary( - '/google.cloud.storageinsights.v1.StorageInsights/DeleteReportConfig', - request_serializer=storageinsights.DeleteReportConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_report_config'] - - @property - def list_report_details(self) -> Callable[ - [storageinsights.ListReportDetailsRequest], - Awaitable[storageinsights.ListReportDetailsResponse]]: - r"""Return a callable for the list report details method over gRPC. - - Lists ReportDetails in a given project and location. - - Returns: - Callable[[~.ListReportDetailsRequest], - Awaitable[~.ListReportDetailsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_report_details' not in self._stubs: - self._stubs['list_report_details'] = self.grpc_channel.unary_unary( - '/google.cloud.storageinsights.v1.StorageInsights/ListReportDetails', - request_serializer=storageinsights.ListReportDetailsRequest.serialize, - response_deserializer=storageinsights.ListReportDetailsResponse.deserialize, - ) - return self._stubs['list_report_details'] - - @property - def get_report_detail(self) -> Callable[ - [storageinsights.GetReportDetailRequest], - Awaitable[storageinsights.ReportDetail]]: - r"""Return a callable for the get report detail method over gRPC. - - Gets details of a single ReportDetail. - - Returns: - Callable[[~.GetReportDetailRequest], - Awaitable[~.ReportDetail]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_report_detail' not in self._stubs: - self._stubs['get_report_detail'] = self.grpc_channel.unary_unary( - '/google.cloud.storageinsights.v1.StorageInsights/GetReportDetail', - request_serializer=storageinsights.GetReportDetailRequest.serialize, - response_deserializer=storageinsights.ReportDetail.deserialize, - ) - return self._stubs['get_report_detail'] - - def close(self): - return self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'StorageInsightsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/rest.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/rest.py deleted file mode 100644 index f28464cddab7..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/services/storage_insights/transports/rest.py +++ /dev/null @@ -1,1475 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.storageinsights_v1.types import storageinsights -from google.protobuf import empty_pb2 # type: ignore - -from .base import StorageInsightsTransport, 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 StorageInsightsRestInterceptor: - """Interceptor for StorageInsights. - - 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 StorageInsightsRestTransport. - - .. code-block:: python - class MyCustomStorageInsightsInterceptor(StorageInsightsRestInterceptor): - def pre_create_report_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_report_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_report_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_report_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_report_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_report_detail(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_report_detail(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_report_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_report_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_report_details(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_report_details(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_report_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_report_config(self, response): - logging.log(f"Received response: {response}") - return response - - transport = StorageInsightsRestTransport(interceptor=MyCustomStorageInsightsInterceptor()) - client = StorageInsightsClient(transport=transport) - - - """ - def pre_create_report_config(self, request: storageinsights.CreateReportConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[storageinsights.CreateReportConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_report_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the StorageInsights server. - """ - return request, metadata - - def post_create_report_config(self, response: storageinsights.ReportConfig) -> storageinsights.ReportConfig: - """Post-rpc interceptor for create_report_config - - Override in a subclass to manipulate the response - after it is returned by the StorageInsights server but before - it is returned to user code. - """ - return response - def pre_delete_report_config(self, request: storageinsights.DeleteReportConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[storageinsights.DeleteReportConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_report_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the StorageInsights server. - """ - return request, metadata - - def pre_get_report_config(self, request: storageinsights.GetReportConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[storageinsights.GetReportConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_report_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the StorageInsights server. - """ - return request, metadata - - def post_get_report_config(self, response: storageinsights.ReportConfig) -> storageinsights.ReportConfig: - """Post-rpc interceptor for get_report_config - - Override in a subclass to manipulate the response - after it is returned by the StorageInsights server but before - it is returned to user code. - """ - return response - def pre_get_report_detail(self, request: storageinsights.GetReportDetailRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[storageinsights.GetReportDetailRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_report_detail - - Override in a subclass to manipulate the request or metadata - before they are sent to the StorageInsights server. - """ - return request, metadata - - def post_get_report_detail(self, response: storageinsights.ReportDetail) -> storageinsights.ReportDetail: - """Post-rpc interceptor for get_report_detail - - Override in a subclass to manipulate the response - after it is returned by the StorageInsights server but before - it is returned to user code. - """ - return response - def pre_list_report_configs(self, request: storageinsights.ListReportConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[storageinsights.ListReportConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_report_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the StorageInsights server. - """ - return request, metadata - - def post_list_report_configs(self, response: storageinsights.ListReportConfigsResponse) -> storageinsights.ListReportConfigsResponse: - """Post-rpc interceptor for list_report_configs - - Override in a subclass to manipulate the response - after it is returned by the StorageInsights server but before - it is returned to user code. - """ - return response - def pre_list_report_details(self, request: storageinsights.ListReportDetailsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[storageinsights.ListReportDetailsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_report_details - - Override in a subclass to manipulate the request or metadata - before they are sent to the StorageInsights server. - """ - return request, metadata - - def post_list_report_details(self, response: storageinsights.ListReportDetailsResponse) -> storageinsights.ListReportDetailsResponse: - """Post-rpc interceptor for list_report_details - - Override in a subclass to manipulate the response - after it is returned by the StorageInsights server but before - it is returned to user code. - """ - return response - def pre_update_report_config(self, request: storageinsights.UpdateReportConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[storageinsights.UpdateReportConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_report_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the StorageInsights server. - """ - return request, metadata - - def post_update_report_config(self, response: storageinsights.ReportConfig) -> storageinsights.ReportConfig: - """Post-rpc interceptor for update_report_config - - Override in a subclass to manipulate the response - after it is returned by the StorageInsights server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the StorageInsights server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the StorageInsights server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the StorageInsights server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the StorageInsights server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the StorageInsights server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the StorageInsights server but before - it is returned to user code. - """ - return response - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the StorageInsights server. - """ - return request, metadata - - def post_delete_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for delete_operation - - Override in a subclass to manipulate the response - after it is returned by the StorageInsights server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the StorageInsights server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the StorageInsights server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the StorageInsights server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the StorageInsights server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class StorageInsightsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: StorageInsightsRestInterceptor - - -class StorageInsightsRestTransport(StorageInsightsTransport): - """REST backend transport for StorageInsights. - - Service describing handlers for resources - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'storageinsights.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[StorageInsightsRestInterceptor] = None, - 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. - - 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 StorageInsightsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateReportConfig(StorageInsightsRestStub): - def __hash__(self): - return hash("CreateReportConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: storageinsights.CreateReportConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> storageinsights.ReportConfig: - r"""Call the create report config method over HTTP. - - Args: - request (~.storageinsights.CreateReportConfigRequest): - The request object. Message for creating a ReportConfig - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.storageinsights.ReportConfig: - Message describing ReportConfig - object. ReportConfig is the - configuration to generate reports. See - https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest - for more details on how to set various - fields. Next ID: 12 - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/reportConfigs', - 'body': 'report_config', - }, - ] - request, metadata = self._interceptor.pre_create_report_config(request, metadata) - pb_request = storageinsights.CreateReportConfigRequest.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=True - ) - 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=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = storageinsights.ReportConfig() - pb_resp = storageinsights.ReportConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_report_config(resp) - return resp - - class _DeleteReportConfig(StorageInsightsRestStub): - def __hash__(self): - return hash("DeleteReportConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: storageinsights.DeleteReportConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete report config method over HTTP. - - Args: - request (~.storageinsights.DeleteReportConfigRequest): - The request object. Message for deleting a ReportConfig - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/reportConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_report_config(request, metadata) - pb_request = storageinsights.DeleteReportConfigRequest.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=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetReportConfig(StorageInsightsRestStub): - def __hash__(self): - return hash("GetReportConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: storageinsights.GetReportConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> storageinsights.ReportConfig: - r"""Call the get report config method over HTTP. - - Args: - request (~.storageinsights.GetReportConfigRequest): - The request object. Message for getting a ReportConfig - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.storageinsights.ReportConfig: - Message describing ReportConfig - object. ReportConfig is the - configuration to generate reports. See - https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest - for more details on how to set various - fields. Next ID: 12 - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/reportConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_get_report_config(request, metadata) - pb_request = storageinsights.GetReportConfigRequest.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=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = storageinsights.ReportConfig() - pb_resp = storageinsights.ReportConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_report_config(resp) - return resp - - class _GetReportDetail(StorageInsightsRestStub): - def __hash__(self): - return hash("GetReportDetail") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: storageinsights.GetReportDetailRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> storageinsights.ReportDetail: - r"""Call the get report detail method over HTTP. - - Args: - request (~.storageinsights.GetReportDetailRequest): - The request object. Message for getting a ReportDetail - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.storageinsights.ReportDetail: - Message describing ReportDetail - object. ReportDetail represents metadata - of generated reports for a ReportConfig. - Next ID: 10 - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/reportConfigs/*/reportDetails/*}', - }, - ] - request, metadata = self._interceptor.pre_get_report_detail(request, metadata) - pb_request = storageinsights.GetReportDetailRequest.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=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = storageinsights.ReportDetail() - pb_resp = storageinsights.ReportDetail.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_report_detail(resp) - return resp - - class _ListReportConfigs(StorageInsightsRestStub): - def __hash__(self): - return hash("ListReportConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: storageinsights.ListReportConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> storageinsights.ListReportConfigsResponse: - r"""Call the list report configs method over HTTP. - - Args: - request (~.storageinsights.ListReportConfigsRequest): - The request object. Message for requesting list of - ReportConfigs - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.storageinsights.ListReportConfigsResponse: - Message for response to listing - ReportConfigs - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/reportConfigs', - }, - ] - request, metadata = self._interceptor.pre_list_report_configs(request, metadata) - pb_request = storageinsights.ListReportConfigsRequest.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=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = storageinsights.ListReportConfigsResponse() - pb_resp = storageinsights.ListReportConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_report_configs(resp) - return resp - - class _ListReportDetails(StorageInsightsRestStub): - def __hash__(self): - return hash("ListReportDetails") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: storageinsights.ListReportDetailsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> storageinsights.ListReportDetailsResponse: - r"""Call the list report details method over HTTP. - - Args: - request (~.storageinsights.ListReportDetailsRequest): - The request object. Message for requesting list of - ReportDetails - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.storageinsights.ListReportDetailsResponse: - Message for response to listing - ReportDetails - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/reportConfigs/*}/reportDetails', - }, - ] - request, metadata = self._interceptor.pre_list_report_details(request, metadata) - pb_request = storageinsights.ListReportDetailsRequest.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=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = storageinsights.ListReportDetailsResponse() - pb_resp = storageinsights.ListReportDetailsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_report_details(resp) - return resp - - class _UpdateReportConfig(StorageInsightsRestStub): - def __hash__(self): - return hash("UpdateReportConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: storageinsights.UpdateReportConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> storageinsights.ReportConfig: - r"""Call the update report config method over HTTP. - - Args: - request (~.storageinsights.UpdateReportConfigRequest): - The request object. Message for updating a ReportConfig - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.storageinsights.ReportConfig: - Message describing ReportConfig - object. ReportConfig is the - configuration to generate reports. See - https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest - for more details on how to set various - fields. Next ID: 12 - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{report_config.name=projects/*/locations/*/reportConfigs/*}', - 'body': 'report_config', - }, - ] - request, metadata = self._interceptor.pre_update_report_config(request, metadata) - pb_request = storageinsights.UpdateReportConfigRequest.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=True - ) - 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=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = storageinsights.ReportConfig() - pb_resp = storageinsights.ReportConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_report_config(resp) - return resp - - @property - def create_report_config(self) -> Callable[ - [storageinsights.CreateReportConfigRequest], - storageinsights.ReportConfig]: - # 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._CreateReportConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_report_config(self) -> Callable[ - [storageinsights.DeleteReportConfigRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteReportConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_report_config(self) -> Callable[ - [storageinsights.GetReportConfigRequest], - storageinsights.ReportConfig]: - # 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._GetReportConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_report_detail(self) -> Callable[ - [storageinsights.GetReportDetailRequest], - storageinsights.ReportDetail]: - # 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._GetReportDetail(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_report_configs(self) -> Callable[ - [storageinsights.ListReportConfigsRequest], - storageinsights.ListReportConfigsResponse]: - # 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._ListReportConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_report_details(self) -> Callable[ - [storageinsights.ListReportDetailsRequest], - storageinsights.ListReportDetailsResponse]: - # 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._ListReportDetails(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_report_config(self) -> Callable[ - [storageinsights.UpdateReportConfigRequest], - storageinsights.ReportConfig]: - # 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._UpdateReportConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(StorageInsightsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['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), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(StorageInsightsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['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), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(StorageInsightsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['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), - 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 self._interceptor.post_cancel_operation(None) - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(StorageInsightsRestStub): - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object for DeleteOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['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), - ) - - # 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 self._interceptor.post_delete_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(StorageInsightsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['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), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(StorageInsightsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['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), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'StorageInsightsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/types/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/types/__init__.py deleted file mode 100644 index 4c456bf92ed7..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/types/__init__.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .storageinsights import ( - CloudStorageDestinationOptions, - CloudStorageFilters, - CreateReportConfigRequest, - CSVOptions, - DeleteReportConfigRequest, - FrequencyOptions, - GetReportConfigRequest, - GetReportDetailRequest, - ListReportConfigsRequest, - ListReportConfigsResponse, - ListReportDetailsRequest, - ListReportDetailsResponse, - ObjectMetadataReportOptions, - OperationMetadata, - ParquetOptions, - ReportConfig, - ReportDetail, - UpdateReportConfigRequest, -) - -__all__ = ( - 'CloudStorageDestinationOptions', - 'CloudStorageFilters', - 'CreateReportConfigRequest', - 'CSVOptions', - 'DeleteReportConfigRequest', - 'FrequencyOptions', - 'GetReportConfigRequest', - 'GetReportDetailRequest', - 'ListReportConfigsRequest', - 'ListReportConfigsResponse', - 'ListReportDetailsRequest', - 'ListReportDetailsResponse', - 'ObjectMetadataReportOptions', - 'OperationMetadata', - 'ParquetOptions', - 'ReportConfig', - 'ReportDetail', - 'UpdateReportConfigRequest', -) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/types/storageinsights.py b/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/types/storageinsights.py deleted file mode 100644 index b26adf510320..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/google/cloud/storageinsights_v1/types/storageinsights.py +++ /dev/null @@ -1,764 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -from google.type import datetime_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.storageinsights.v1', - manifest={ - 'ListReportConfigsRequest', - 'ListReportConfigsResponse', - 'GetReportConfigRequest', - 'CreateReportConfigRequest', - 'UpdateReportConfigRequest', - 'DeleteReportConfigRequest', - 'ReportDetail', - 'ListReportDetailsRequest', - 'ListReportDetailsResponse', - 'GetReportDetailRequest', - 'OperationMetadata', - 'FrequencyOptions', - 'CSVOptions', - 'ParquetOptions', - 'CloudStorageFilters', - 'CloudStorageDestinationOptions', - 'ObjectMetadataReportOptions', - 'ReportConfig', - }, -) - - -class ListReportConfigsRequest(proto.Message): - r"""Message for requesting list of ReportConfigs - - Attributes: - parent (str): - Required. Parent value for - ListReportConfigsRequest - page_size (int): - Requested page size. Server may return fewer - items than requested. If unspecified, server - will pick an appropriate default. - page_token (str): - A token identifying a page of results the - server should return. - filter (str): - Filtering results - order_by (str): - Hint for how to order the results - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListReportConfigsResponse(proto.Message): - r"""Message for response to listing ReportConfigs - - Attributes: - report_configs (MutableSequence[google.cloud.storageinsights_v1.types.ReportConfig]): - The list of ReportConfig - next_page_token (str): - A token identifying a page of results the - server should return. - unreachable (MutableSequence[str]): - Locations that could not be reached. - """ - - @property - def raw_page(self): - return self - - report_configs: MutableSequence['ReportConfig'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ReportConfig', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class GetReportConfigRequest(proto.Message): - r"""Message for getting a ReportConfig - - Attributes: - name (str): - Required. Name of the resource - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateReportConfigRequest(proto.Message): - r"""Message for creating a ReportConfig - - Attributes: - parent (str): - Required. Value for parent. - report_config (google.cloud.storageinsights_v1.types.ReportConfig): - Required. The resource being created - request_id (str): - Optional. An optional request ID to identify - requests. Specify a unique request ID so that if - you must retry your request, the server will - know to ignore the request if it has already - been completed. The server will guarantee that - for at least 60 minutes since the first request. - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. - The request ID must be a valid UUID with the - exception that zero UUID is not supported - (00000000-0000-0000-0000-000000000000). - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - report_config: 'ReportConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='ReportConfig', - ) - request_id: str = proto.Field( - proto.STRING, - number=4, - ) - - -class UpdateReportConfigRequest(proto.Message): - r"""Message for updating a ReportConfig - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Field mask is used to specify the fields to be - overwritten in the ReportConfig resource by the update. The - fields specified in the update_mask are relative to the - resource, not the full request. A field will be overwritten - if it is in the mask. If the user does not provide a mask - then all fields will be overwritten. - report_config (google.cloud.storageinsights_v1.types.ReportConfig): - Required. The resource being updated - request_id (str): - Optional. An optional request ID to identify - requests. Specify a unique request ID so that if - you must retry your request, the server will - know to ignore the request if it has already - been completed. The server will guarantee that - for at least 60 minutes since the first request. - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. - The request ID must be a valid UUID with the - exception that zero UUID is not supported - (00000000-0000-0000-0000-000000000000). - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - report_config: 'ReportConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='ReportConfig', - ) - request_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class DeleteReportConfigRequest(proto.Message): - r"""Message for deleting a ReportConfig - - Attributes: - name (str): - Required. Name of the resource - force (bool): - Optional. If set, all ReportDetails for this - ReportConfig will be deleted. - request_id (str): - Optional. An optional request ID to identify - requests. Specify a unique request ID so that if - you must retry your request, the server will - know to ignore the request if it has already - been completed. The server will guarantee that - for at least 60 minutes after the first request. - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. - The request ID must be a valid UUID with the - exception that zero UUID is not supported - (00000000-0000-0000-0000-000000000000). - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - force: bool = proto.Field( - proto.BOOL, - number=2, - ) - request_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ReportDetail(proto.Message): - r"""Message describing ReportDetail object. ReportDetail - represents metadata of generated reports for a ReportConfig. - Next ID: 10 - - Attributes: - name (str): - Name of resource. It will be of form - projects//locations//reportConfigs//reportDetails/. - snapshot_time (google.protobuf.timestamp_pb2.Timestamp): - The snapshot time. - All the report data is referenced at this point - of time. - report_path_prefix (str): - Prefix of the object name of each report's shard. This will - have full prefix except the "extension" and "shard_id". For - example, if the ``destination_path`` is - ``{{report-config-id}}/dt={{datetime}}``, the shard object - name would be - ``gs://my-insights/1A34-F2E456-12B456-1C3D/dt=2022-05-20T06:35/1A34-F2E456-12B456-1C3D_2022-05-20T06:35_5.csv`` - and the value of ``report_path_prefix`` field would be - ``gs://my-insights/1A34-F2E456-12B456-1C3D/dt=2022-05-20T06:35/1A34-F2E456-12B456-1C3D_2022-05-20T06:35_``. - shards_count (int): - Total shards generated for the report. - status (google.rpc.status_pb2.Status): - Status of the ReportDetail. - labels (MutableMapping[str, str]): - Labels as key value pairs - target_datetime (google.type.datetime_pb2.DateTime): - The date for which report is generated. The time part of - target_datetime will be zero till we support multiple - reports per day. - report_metrics (google.cloud.storageinsights_v1.types.ReportDetail.Metrics): - Metrics of the report. - """ - - class Metrics(proto.Message): - r"""Different metrics associated with the generated report. - - Attributes: - processed_records_count (int): - Count of Cloud Storage objects which are part - of the report. - """ - - processed_records_count: int = proto.Field( - proto.INT64, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - snapshot_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - report_path_prefix: str = proto.Field( - proto.STRING, - number=8, - ) - shards_count: int = proto.Field( - proto.INT64, - number=9, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=4, - message=status_pb2.Status, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - target_datetime: datetime_pb2.DateTime = proto.Field( - proto.MESSAGE, - number=6, - message=datetime_pb2.DateTime, - ) - report_metrics: Metrics = proto.Field( - proto.MESSAGE, - number=7, - message=Metrics, - ) - - -class ListReportDetailsRequest(proto.Message): - r"""Message for requesting list of ReportDetails - - Attributes: - parent (str): - Required. Parent value for - ListReportDetailsRequest - page_size (int): - Requested page size. Server may return fewer - items than requested. If unspecified, server - will pick an appropriate default. - page_token (str): - A token identifying a page of results the - server should return. - filter (str): - Filtering results - order_by (str): - Hint for how to order the results - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListReportDetailsResponse(proto.Message): - r"""Message for response to listing ReportDetails - - Attributes: - report_details (MutableSequence[google.cloud.storageinsights_v1.types.ReportDetail]): - The list of ReportDetail - next_page_token (str): - A token identifying a page of results the - server should return. - unreachable (MutableSequence[str]): - Locations that could not be reached. - """ - - @property - def raw_page(self): - return self - - report_details: MutableSequence['ReportDetail'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ReportDetail', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class GetReportDetailRequest(proto.Message): - r"""Message for getting a ReportDetail - - Attributes: - name (str): - Required. Name of the resource - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class OperationMetadata(proto.Message): - r"""Represents the metadata of the long-running operation. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the operation was - created. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the operation finished - running. - target (str): - Output only. Server-defined resource path for - the target of the operation. - verb (str): - Output only. Name of the verb executed by the - operation. - status_message (str): - Output only. Human-readable status of the - operation, if any. - requested_cancellation (bool): - Output only. Identifies whether the user has requested - cancellation of the operation. Operations that have been - cancelled successfully have [Operation.error][] value with a - [google.rpc.Status.code][google.rpc.Status.code] of 1, - corresponding to ``Code.CANCELLED``. - api_version (str): - Output only. API version used to start the - operation. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - target: str = proto.Field( - proto.STRING, - number=3, - ) - verb: str = proto.Field( - proto.STRING, - number=4, - ) - status_message: str = proto.Field( - proto.STRING, - number=5, - ) - requested_cancellation: bool = proto.Field( - proto.BOOL, - number=6, - ) - api_version: str = proto.Field( - proto.STRING, - number=7, - ) - - -class FrequencyOptions(proto.Message): - r"""ReportConfig Resource: - - Options to setup frequency of report generation. - - Attributes: - frequency (google.cloud.storageinsights_v1.types.FrequencyOptions.Frequency): - Frequency of report generation. - start_date (google.type.date_pb2.Date): - The date from which report generation should - start. UTC time zone. - end_date (google.type.date_pb2.Date): - The date on which report generation should - stop (Inclusive). UTC time zone. - """ - class Frequency(proto.Enum): - r"""This ENUM specifies possible frequencies of report - generation. - - Values: - FREQUENCY_UNSPECIFIED (0): - Unspecified. - DAILY (1): - Report will be generated daily. - WEEKLY (2): - Report will be generated weekly. - """ - FREQUENCY_UNSPECIFIED = 0 - DAILY = 1 - WEEKLY = 2 - - frequency: Frequency = proto.Field( - proto.ENUM, - number=1, - enum=Frequency, - ) - start_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=2, - message=date_pb2.Date, - ) - end_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=3, - message=date_pb2.Date, - ) - - -class CSVOptions(proto.Message): - r"""Options to configure CSV formatted reports. - - Attributes: - record_separator (str): - Record separator characters in CSV. - delimiter (str): - Delimiter characters in CSV. - header_required (bool): - If set, will include a header row in the CSV - report. - """ - - record_separator: str = proto.Field( - proto.STRING, - number=1, - ) - delimiter: str = proto.Field( - proto.STRING, - number=2, - ) - header_required: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class ParquetOptions(proto.Message): - r"""Options to configure Parquet formatted reports. - """ - - -class CloudStorageFilters(proto.Message): - r"""Options to filter data on storage systems. - Next ID: 2 - - Attributes: - bucket (str): - Bucket for which the report will be - generated. - """ - - bucket: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CloudStorageDestinationOptions(proto.Message): - r"""Options to store reports in storage systems. - Next ID: 3 - - Attributes: - bucket (str): - Destination bucket. - destination_path (str): - Destination path is the path in the bucket - where the report should be generated. - """ - - bucket: str = proto.Field( - proto.STRING, - number=1, - ) - destination_path: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ObjectMetadataReportOptions(proto.Message): - r"""Report specification for exporting object metadata. - Next ID: 4 - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - metadata_fields (MutableSequence[str]): - Metadata fields to be included in the report. - storage_filters (google.cloud.storageinsights_v1.types.CloudStorageFilters): - Cloud Storage as the storage system. - - This field is a member of `oneof`_ ``filter``. - storage_destination_options (google.cloud.storageinsights_v1.types.CloudStorageDestinationOptions): - Cloud Storage as the storage system. - - This field is a member of `oneof`_ ``destination_options``. - """ - - metadata_fields: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - storage_filters: 'CloudStorageFilters' = proto.Field( - proto.MESSAGE, - number=2, - oneof='filter', - message='CloudStorageFilters', - ) - storage_destination_options: 'CloudStorageDestinationOptions' = proto.Field( - proto.MESSAGE, - number=3, - oneof='destination_options', - message='CloudStorageDestinationOptions', - ) - - -class ReportConfig(proto.Message): - r"""Message describing ReportConfig object. ReportConfig is the - configuration to generate reports. - See - https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest - for more details on how to set various fields. - Next ID: 12 - - 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): - name of resource. It will be of form - projects//locations//reportConfigs/. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. [Output only] Create time stamp - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. [Output only] Update time stamp - frequency_options (google.cloud.storageinsights_v1.types.FrequencyOptions): - The frequency of report generation. - csv_options (google.cloud.storageinsights_v1.types.CSVOptions): - Options for CSV formatted reports. - - This field is a member of `oneof`_ ``report_format``. - parquet_options (google.cloud.storageinsights_v1.types.ParquetOptions): - Options for Parquet formatted reports. - - This field is a member of `oneof`_ ``report_format``. - object_metadata_report_options (google.cloud.storageinsights_v1.types.ObjectMetadataReportOptions): - Report for exporting object metadata. - - This field is a member of `oneof`_ ``report_kind``. - labels (MutableMapping[str, str]): - Labels as key value pairs - display_name (str): - User provided display name which can be empty - and limited to 256 characters that is editable. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - frequency_options: 'FrequencyOptions' = proto.Field( - proto.MESSAGE, - number=5, - message='FrequencyOptions', - ) - csv_options: 'CSVOptions' = proto.Field( - proto.MESSAGE, - number=6, - oneof='report_format', - message='CSVOptions', - ) - parquet_options: 'ParquetOptions' = proto.Field( - proto.MESSAGE, - number=7, - oneof='report_format', - message='ParquetOptions', - ) - object_metadata_report_options: 'ObjectMetadataReportOptions' = proto.Field( - proto.MESSAGE, - number=8, - oneof='report_kind', - message='ObjectMetadataReportOptions', - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=10, - ) - display_name: str = proto.Field( - proto.STRING, - number=11, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/mypy.ini b/owl-bot-staging/google-cloud-storageinsights/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/noxfile.py b/owl-bot-staging/google-cloud-storageinsights/v1/noxfile.py deleted file mode 100644 index bace531aed7c..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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", - "3.11", -] - -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.11" - -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/cloud/storageinsights_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--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/google-cloud-storageinsights/v1/samples/generated_samples/snippet_metadata_google.cloud.storageinsights.v1.json b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/snippet_metadata_google.cloud.storageinsights.v1.json deleted file mode 100644 index 7411c6d3c4bf..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/snippet_metadata_google.cloud.storageinsights.v1.json +++ /dev/null @@ -1,1152 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.storageinsights.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-storageinsights", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient", - "shortName": "StorageInsightsAsyncClient" - }, - "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient.create_report_config", - "method": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights.CreateReportConfig", - "service": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights", - "shortName": "StorageInsights" - }, - "shortName": "CreateReportConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.storageinsights_v1.types.CreateReportConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "report_config", - "type": "google.cloud.storageinsights_v1.types.ReportConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.storageinsights_v1.types.ReportConfig", - "shortName": "create_report_config" - }, - "description": "Sample for CreateReportConfig", - "file": "storageinsights_v1_generated_storage_insights_create_report_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "storageinsights_v1_generated_StorageInsights_CreateReportConfig_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": "storageinsights_v1_generated_storage_insights_create_report_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient", - "shortName": "StorageInsightsClient" - }, - "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient.create_report_config", - "method": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights.CreateReportConfig", - "service": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights", - "shortName": "StorageInsights" - }, - "shortName": "CreateReportConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.storageinsights_v1.types.CreateReportConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "report_config", - "type": "google.cloud.storageinsights_v1.types.ReportConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.storageinsights_v1.types.ReportConfig", - "shortName": "create_report_config" - }, - "description": "Sample for CreateReportConfig", - "file": "storageinsights_v1_generated_storage_insights_create_report_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "storageinsights_v1_generated_StorageInsights_CreateReportConfig_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": "storageinsights_v1_generated_storage_insights_create_report_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient", - "shortName": "StorageInsightsAsyncClient" - }, - "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient.delete_report_config", - "method": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights.DeleteReportConfig", - "service": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights", - "shortName": "StorageInsights" - }, - "shortName": "DeleteReportConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.storageinsights_v1.types.DeleteReportConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_report_config" - }, - "description": "Sample for DeleteReportConfig", - "file": "storageinsights_v1_generated_storage_insights_delete_report_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "storageinsights_v1_generated_StorageInsights_DeleteReportConfig_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "storageinsights_v1_generated_storage_insights_delete_report_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient", - "shortName": "StorageInsightsClient" - }, - "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient.delete_report_config", - "method": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights.DeleteReportConfig", - "service": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights", - "shortName": "StorageInsights" - }, - "shortName": "DeleteReportConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.storageinsights_v1.types.DeleteReportConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_report_config" - }, - "description": "Sample for DeleteReportConfig", - "file": "storageinsights_v1_generated_storage_insights_delete_report_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "storageinsights_v1_generated_StorageInsights_DeleteReportConfig_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "storageinsights_v1_generated_storage_insights_delete_report_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient", - "shortName": "StorageInsightsAsyncClient" - }, - "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient.get_report_config", - "method": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights.GetReportConfig", - "service": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights", - "shortName": "StorageInsights" - }, - "shortName": "GetReportConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.storageinsights_v1.types.GetReportConfigRequest" - }, - { - "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.cloud.storageinsights_v1.types.ReportConfig", - "shortName": "get_report_config" - }, - "description": "Sample for GetReportConfig", - "file": "storageinsights_v1_generated_storage_insights_get_report_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "storageinsights_v1_generated_StorageInsights_GetReportConfig_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": "storageinsights_v1_generated_storage_insights_get_report_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient", - "shortName": "StorageInsightsClient" - }, - "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient.get_report_config", - "method": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights.GetReportConfig", - "service": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights", - "shortName": "StorageInsights" - }, - "shortName": "GetReportConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.storageinsights_v1.types.GetReportConfigRequest" - }, - { - "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.cloud.storageinsights_v1.types.ReportConfig", - "shortName": "get_report_config" - }, - "description": "Sample for GetReportConfig", - "file": "storageinsights_v1_generated_storage_insights_get_report_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "storageinsights_v1_generated_StorageInsights_GetReportConfig_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": "storageinsights_v1_generated_storage_insights_get_report_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient", - "shortName": "StorageInsightsAsyncClient" - }, - "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient.get_report_detail", - "method": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights.GetReportDetail", - "service": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights", - "shortName": "StorageInsights" - }, - "shortName": "GetReportDetail" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.storageinsights_v1.types.GetReportDetailRequest" - }, - { - "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.cloud.storageinsights_v1.types.ReportDetail", - "shortName": "get_report_detail" - }, - "description": "Sample for GetReportDetail", - "file": "storageinsights_v1_generated_storage_insights_get_report_detail_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "storageinsights_v1_generated_StorageInsights_GetReportDetail_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": "storageinsights_v1_generated_storage_insights_get_report_detail_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient", - "shortName": "StorageInsightsClient" - }, - "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient.get_report_detail", - "method": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights.GetReportDetail", - "service": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights", - "shortName": "StorageInsights" - }, - "shortName": "GetReportDetail" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.storageinsights_v1.types.GetReportDetailRequest" - }, - { - "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.cloud.storageinsights_v1.types.ReportDetail", - "shortName": "get_report_detail" - }, - "description": "Sample for GetReportDetail", - "file": "storageinsights_v1_generated_storage_insights_get_report_detail_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "storageinsights_v1_generated_StorageInsights_GetReportDetail_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": "storageinsights_v1_generated_storage_insights_get_report_detail_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient", - "shortName": "StorageInsightsAsyncClient" - }, - "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient.list_report_configs", - "method": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights.ListReportConfigs", - "service": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights", - "shortName": "StorageInsights" - }, - "shortName": "ListReportConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.storageinsights_v1.types.ListReportConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.storageinsights_v1.services.storage_insights.pagers.ListReportConfigsAsyncPager", - "shortName": "list_report_configs" - }, - "description": "Sample for ListReportConfigs", - "file": "storageinsights_v1_generated_storage_insights_list_report_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "storageinsights_v1_generated_StorageInsights_ListReportConfigs_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "storageinsights_v1_generated_storage_insights_list_report_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient", - "shortName": "StorageInsightsClient" - }, - "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient.list_report_configs", - "method": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights.ListReportConfigs", - "service": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights", - "shortName": "StorageInsights" - }, - "shortName": "ListReportConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.storageinsights_v1.types.ListReportConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.storageinsights_v1.services.storage_insights.pagers.ListReportConfigsPager", - "shortName": "list_report_configs" - }, - "description": "Sample for ListReportConfigs", - "file": "storageinsights_v1_generated_storage_insights_list_report_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "storageinsights_v1_generated_StorageInsights_ListReportConfigs_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "storageinsights_v1_generated_storage_insights_list_report_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient", - "shortName": "StorageInsightsAsyncClient" - }, - "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient.list_report_details", - "method": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights.ListReportDetails", - "service": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights", - "shortName": "StorageInsights" - }, - "shortName": "ListReportDetails" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.storageinsights_v1.types.ListReportDetailsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.storageinsights_v1.services.storage_insights.pagers.ListReportDetailsAsyncPager", - "shortName": "list_report_details" - }, - "description": "Sample for ListReportDetails", - "file": "storageinsights_v1_generated_storage_insights_list_report_details_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "storageinsights_v1_generated_StorageInsights_ListReportDetails_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "storageinsights_v1_generated_storage_insights_list_report_details_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient", - "shortName": "StorageInsightsClient" - }, - "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient.list_report_details", - "method": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights.ListReportDetails", - "service": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights", - "shortName": "StorageInsights" - }, - "shortName": "ListReportDetails" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.storageinsights_v1.types.ListReportDetailsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.storageinsights_v1.services.storage_insights.pagers.ListReportDetailsPager", - "shortName": "list_report_details" - }, - "description": "Sample for ListReportDetails", - "file": "storageinsights_v1_generated_storage_insights_list_report_details_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "storageinsights_v1_generated_StorageInsights_ListReportDetails_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "storageinsights_v1_generated_storage_insights_list_report_details_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient", - "shortName": "StorageInsightsAsyncClient" - }, - "fullName": "google.cloud.storageinsights_v1.StorageInsightsAsyncClient.update_report_config", - "method": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights.UpdateReportConfig", - "service": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights", - "shortName": "StorageInsights" - }, - "shortName": "UpdateReportConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.storageinsights_v1.types.UpdateReportConfigRequest" - }, - { - "name": "report_config", - "type": "google.cloud.storageinsights_v1.types.ReportConfig" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.storageinsights_v1.types.ReportConfig", - "shortName": "update_report_config" - }, - "description": "Sample for UpdateReportConfig", - "file": "storageinsights_v1_generated_storage_insights_update_report_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "storageinsights_v1_generated_StorageInsights_UpdateReportConfig_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": "storageinsights_v1_generated_storage_insights_update_report_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient", - "shortName": "StorageInsightsClient" - }, - "fullName": "google.cloud.storageinsights_v1.StorageInsightsClient.update_report_config", - "method": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights.UpdateReportConfig", - "service": { - "fullName": "google.cloud.storageinsights.v1.StorageInsights", - "shortName": "StorageInsights" - }, - "shortName": "UpdateReportConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.storageinsights_v1.types.UpdateReportConfigRequest" - }, - { - "name": "report_config", - "type": "google.cloud.storageinsights_v1.types.ReportConfig" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.storageinsights_v1.types.ReportConfig", - "shortName": "update_report_config" - }, - "description": "Sample for UpdateReportConfig", - "file": "storageinsights_v1_generated_storage_insights_update_report_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "storageinsights_v1_generated_StorageInsights_UpdateReportConfig_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": "storageinsights_v1_generated_storage_insights_update_report_config_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_create_report_config_async.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_create_report_config_async.py deleted file mode 100644 index 53d12ea780f5..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_create_report_config_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 CreateReportConfig -# 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-cloud-storageinsights - - -# [START storageinsights_v1_generated_StorageInsights_CreateReportConfig_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.cloud import storageinsights_v1 - - -async def sample_create_report_config(): - # Create a client - client = storageinsights_v1.StorageInsightsAsyncClient() - - # Initialize request argument(s) - request = storageinsights_v1.CreateReportConfigRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_report_config(request=request) - - # Handle the response - print(response) - -# [END storageinsights_v1_generated_StorageInsights_CreateReportConfig_async] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_create_report_config_sync.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_create_report_config_sync.py deleted file mode 100644 index 3d46d0af8672..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_create_report_config_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 CreateReportConfig -# 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-cloud-storageinsights - - -# [START storageinsights_v1_generated_StorageInsights_CreateReportConfig_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.cloud import storageinsights_v1 - - -def sample_create_report_config(): - # Create a client - client = storageinsights_v1.StorageInsightsClient() - - # Initialize request argument(s) - request = storageinsights_v1.CreateReportConfigRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_report_config(request=request) - - # Handle the response - print(response) - -# [END storageinsights_v1_generated_StorageInsights_CreateReportConfig_sync] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_delete_report_config_async.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_delete_report_config_async.py deleted file mode 100644 index a9c946397b67..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_delete_report_config_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 DeleteReportConfig -# 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-cloud-storageinsights - - -# [START storageinsights_v1_generated_StorageInsights_DeleteReportConfig_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.cloud import storageinsights_v1 - - -async def sample_delete_report_config(): - # Create a client - client = storageinsights_v1.StorageInsightsAsyncClient() - - # Initialize request argument(s) - request = storageinsights_v1.DeleteReportConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_report_config(request=request) - - -# [END storageinsights_v1_generated_StorageInsights_DeleteReportConfig_async] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_delete_report_config_sync.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_delete_report_config_sync.py deleted file mode 100644 index 17ab407e9252..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_delete_report_config_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 DeleteReportConfig -# 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-cloud-storageinsights - - -# [START storageinsights_v1_generated_StorageInsights_DeleteReportConfig_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.cloud import storageinsights_v1 - - -def sample_delete_report_config(): - # Create a client - client = storageinsights_v1.StorageInsightsClient() - - # Initialize request argument(s) - request = storageinsights_v1.DeleteReportConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_report_config(request=request) - - -# [END storageinsights_v1_generated_StorageInsights_DeleteReportConfig_sync] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_config_async.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_config_async.py deleted file mode 100644 index 8646f2ffa887..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_config_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 GetReportConfig -# 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-cloud-storageinsights - - -# [START storageinsights_v1_generated_StorageInsights_GetReportConfig_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.cloud import storageinsights_v1 - - -async def sample_get_report_config(): - # Create a client - client = storageinsights_v1.StorageInsightsAsyncClient() - - # Initialize request argument(s) - request = storageinsights_v1.GetReportConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_report_config(request=request) - - # Handle the response - print(response) - -# [END storageinsights_v1_generated_StorageInsights_GetReportConfig_async] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_config_sync.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_config_sync.py deleted file mode 100644 index 877b6fb331fb..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_config_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 GetReportConfig -# 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-cloud-storageinsights - - -# [START storageinsights_v1_generated_StorageInsights_GetReportConfig_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.cloud import storageinsights_v1 - - -def sample_get_report_config(): - # Create a client - client = storageinsights_v1.StorageInsightsClient() - - # Initialize request argument(s) - request = storageinsights_v1.GetReportConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_report_config(request=request) - - # Handle the response - print(response) - -# [END storageinsights_v1_generated_StorageInsights_GetReportConfig_sync] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_detail_async.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_detail_async.py deleted file mode 100644 index 3c3631e3d55b..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_detail_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 GetReportDetail -# 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-cloud-storageinsights - - -# [START storageinsights_v1_generated_StorageInsights_GetReportDetail_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.cloud import storageinsights_v1 - - -async def sample_get_report_detail(): - # Create a client - client = storageinsights_v1.StorageInsightsAsyncClient() - - # Initialize request argument(s) - request = storageinsights_v1.GetReportDetailRequest( - name="name_value", - ) - - # Make the request - response = await client.get_report_detail(request=request) - - # Handle the response - print(response) - -# [END storageinsights_v1_generated_StorageInsights_GetReportDetail_async] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_detail_sync.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_detail_sync.py deleted file mode 100644 index 32fab15fd035..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_get_report_detail_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 GetReportDetail -# 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-cloud-storageinsights - - -# [START storageinsights_v1_generated_StorageInsights_GetReportDetail_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.cloud import storageinsights_v1 - - -def sample_get_report_detail(): - # Create a client - client = storageinsights_v1.StorageInsightsClient() - - # Initialize request argument(s) - request = storageinsights_v1.GetReportDetailRequest( - name="name_value", - ) - - # Make the request - response = client.get_report_detail(request=request) - - # Handle the response - print(response) - -# [END storageinsights_v1_generated_StorageInsights_GetReportDetail_sync] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_configs_async.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_configs_async.py deleted file mode 100644 index 5e5e6de3caa1..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_configs_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 ListReportConfigs -# 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-cloud-storageinsights - - -# [START storageinsights_v1_generated_StorageInsights_ListReportConfigs_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.cloud import storageinsights_v1 - - -async def sample_list_report_configs(): - # Create a client - client = storageinsights_v1.StorageInsightsAsyncClient() - - # Initialize request argument(s) - request = storageinsights_v1.ListReportConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_report_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END storageinsights_v1_generated_StorageInsights_ListReportConfigs_async] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_configs_sync.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_configs_sync.py deleted file mode 100644 index 5b291bac8c4c..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_configs_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 ListReportConfigs -# 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-cloud-storageinsights - - -# [START storageinsights_v1_generated_StorageInsights_ListReportConfigs_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.cloud import storageinsights_v1 - - -def sample_list_report_configs(): - # Create a client - client = storageinsights_v1.StorageInsightsClient() - - # Initialize request argument(s) - request = storageinsights_v1.ListReportConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_report_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END storageinsights_v1_generated_StorageInsights_ListReportConfigs_sync] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_details_async.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_details_async.py deleted file mode 100644 index 6d922f937cfa..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_details_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 ListReportDetails -# 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-cloud-storageinsights - - -# [START storageinsights_v1_generated_StorageInsights_ListReportDetails_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.cloud import storageinsights_v1 - - -async def sample_list_report_details(): - # Create a client - client = storageinsights_v1.StorageInsightsAsyncClient() - - # Initialize request argument(s) - request = storageinsights_v1.ListReportDetailsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_report_details(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END storageinsights_v1_generated_StorageInsights_ListReportDetails_async] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_details_sync.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_details_sync.py deleted file mode 100644 index fcb37ad4a4ec..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_list_report_details_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 ListReportDetails -# 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-cloud-storageinsights - - -# [START storageinsights_v1_generated_StorageInsights_ListReportDetails_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.cloud import storageinsights_v1 - - -def sample_list_report_details(): - # Create a client - client = storageinsights_v1.StorageInsightsClient() - - # Initialize request argument(s) - request = storageinsights_v1.ListReportDetailsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_report_details(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END storageinsights_v1_generated_StorageInsights_ListReportDetails_sync] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_update_report_config_async.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_update_report_config_async.py deleted file mode 100644 index a874104b638e..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_update_report_config_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 UpdateReportConfig -# 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-cloud-storageinsights - - -# [START storageinsights_v1_generated_StorageInsights_UpdateReportConfig_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.cloud import storageinsights_v1 - - -async def sample_update_report_config(): - # Create a client - client = storageinsights_v1.StorageInsightsAsyncClient() - - # Initialize request argument(s) - request = storageinsights_v1.UpdateReportConfigRequest( - ) - - # Make the request - response = await client.update_report_config(request=request) - - # Handle the response - print(response) - -# [END storageinsights_v1_generated_StorageInsights_UpdateReportConfig_async] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_update_report_config_sync.py b/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_update_report_config_sync.py deleted file mode 100644 index 03071db6140e..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/samples/generated_samples/storageinsights_v1_generated_storage_insights_update_report_config_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 UpdateReportConfig -# 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-cloud-storageinsights - - -# [START storageinsights_v1_generated_StorageInsights_UpdateReportConfig_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.cloud import storageinsights_v1 - - -def sample_update_report_config(): - # Create a client - client = storageinsights_v1.StorageInsightsClient() - - # Initialize request argument(s) - request = storageinsights_v1.UpdateReportConfigRequest( - ) - - # Make the request - response = client.update_report_config(request=request) - - # Handle the response - print(response) - -# [END storageinsights_v1_generated_StorageInsights_UpdateReportConfig_sync] diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/scripts/fixup_storageinsights_v1_keywords.py b/owl-bot-staging/google-cloud-storageinsights/v1/scripts/fixup_storageinsights_v1_keywords.py deleted file mode 100644 index ea93709df957..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/scripts/fixup_storageinsights_v1_keywords.py +++ /dev/null @@ -1,182 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 storageinsightsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_report_config': ('parent', 'report_config', 'request_id', ), - 'delete_report_config': ('name', 'force', 'request_id', ), - 'get_report_config': ('name', ), - 'get_report_detail': ('name', ), - 'list_report_configs': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_report_details': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'update_report_config': ('update_mask', 'report_config', 'request_id', ), - } - - 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=storageinsightsCallTransformer(), -): - """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 storageinsights client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/setup.py b/owl-bot-staging/google-cloud-storageinsights/v1/setup.py deleted file mode 100644 index bce5e7831667..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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-cloud-storageinsights' - - -description = "Google Cloud Storageinsights API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/storageinsights/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.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "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-storageinsights" - -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", "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", - "Programming Language :: Python :: 3.11", - "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/google-cloud-storageinsights/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/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/google-cloud-storageinsights/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/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/google-cloud-storageinsights/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.12.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/google-cloud-storageinsights/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.7.txt deleted file mode 100644 index 6c44adfea7ee..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,9 +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 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/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/google-cloud-storageinsights/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-storageinsights/v1/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/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/google-cloud-storageinsights/v1/tests/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/tests/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/storageinsights_v1/__init__.py b/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/storageinsights_v1/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/storageinsights_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/storageinsights_v1/test_storage_insights.py b/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/storageinsights_v1/test_storage_insights.py deleted file mode 100644 index fcc37c2e1b3e..000000000000 --- a/owl-bot-staging/google-cloud-storageinsights/v1/tests/unit/gapic/storageinsights_v1/test_storage_insights.py +++ /dev/null @@ -1,6142 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.location import locations_pb2 -from google.cloud.storageinsights_v1.services.storage_insights import StorageInsightsAsyncClient -from google.cloud.storageinsights_v1.services.storage_insights import StorageInsightsClient -from google.cloud.storageinsights_v1.services.storage_insights import pagers -from google.cloud.storageinsights_v1.services.storage_insights import transports -from google.cloud.storageinsights_v1.types import storageinsights -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -from google.type import datetime_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 StorageInsightsClient._get_default_mtls_endpoint(None) is None - assert StorageInsightsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert StorageInsightsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert StorageInsightsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert StorageInsightsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert StorageInsightsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (StorageInsightsClient, "grpc"), - (StorageInsightsAsyncClient, "grpc_asyncio"), - (StorageInsightsClient, "rest"), -]) -def test_storage_insights_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 == ( - 'storageinsights.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://storageinsights.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.StorageInsightsGrpcTransport, "grpc"), - (transports.StorageInsightsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.StorageInsightsRestTransport, "rest"), -]) -def test_storage_insights_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", [ - (StorageInsightsClient, "grpc"), - (StorageInsightsAsyncClient, "grpc_asyncio"), - (StorageInsightsClient, "rest"), -]) -def test_storage_insights_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 == ( - 'storageinsights.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://storageinsights.googleapis.com' - ) - - -def test_storage_insights_client_get_transport_class(): - transport = StorageInsightsClient.get_transport_class() - available_transports = [ - transports.StorageInsightsGrpcTransport, - transports.StorageInsightsRestTransport, - ] - assert transport in available_transports - - transport = StorageInsightsClient.get_transport_class("grpc") - assert transport == transports.StorageInsightsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (StorageInsightsClient, transports.StorageInsightsGrpcTransport, "grpc"), - (StorageInsightsAsyncClient, transports.StorageInsightsGrpcAsyncIOTransport, "grpc_asyncio"), - (StorageInsightsClient, transports.StorageInsightsRestTransport, "rest"), -]) -@mock.patch.object(StorageInsightsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StorageInsightsClient)) -@mock.patch.object(StorageInsightsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StorageInsightsAsyncClient)) -def test_storage_insights_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(StorageInsightsClient, '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(StorageInsightsClient, '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", [ - (StorageInsightsClient, transports.StorageInsightsGrpcTransport, "grpc", "true"), - (StorageInsightsAsyncClient, transports.StorageInsightsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (StorageInsightsClient, transports.StorageInsightsGrpcTransport, "grpc", "false"), - (StorageInsightsAsyncClient, transports.StorageInsightsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (StorageInsightsClient, transports.StorageInsightsRestTransport, "rest", "true"), - (StorageInsightsClient, transports.StorageInsightsRestTransport, "rest", "false"), -]) -@mock.patch.object(StorageInsightsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StorageInsightsClient)) -@mock.patch.object(StorageInsightsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StorageInsightsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_storage_insights_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", [ - StorageInsightsClient, StorageInsightsAsyncClient -]) -@mock.patch.object(StorageInsightsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StorageInsightsClient)) -@mock.patch.object(StorageInsightsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StorageInsightsAsyncClient)) -def test_storage_insights_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", [ - (StorageInsightsClient, transports.StorageInsightsGrpcTransport, "grpc"), - (StorageInsightsAsyncClient, transports.StorageInsightsGrpcAsyncIOTransport, "grpc_asyncio"), - (StorageInsightsClient, transports.StorageInsightsRestTransport, "rest"), -]) -def test_storage_insights_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", [ - (StorageInsightsClient, transports.StorageInsightsGrpcTransport, "grpc", grpc_helpers), - (StorageInsightsAsyncClient, transports.StorageInsightsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (StorageInsightsClient, transports.StorageInsightsRestTransport, "rest", None), -]) -def test_storage_insights_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_storage_insights_client_client_options_from_dict(): - with mock.patch('google.cloud.storageinsights_v1.services.storage_insights.transports.StorageInsightsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = StorageInsightsClient( - 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", [ - (StorageInsightsClient, transports.StorageInsightsGrpcTransport, "grpc", grpc_helpers), - (StorageInsightsAsyncClient, transports.StorageInsightsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_storage_insights_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( - "storageinsights.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="storageinsights.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - storageinsights.ListReportConfigsRequest, - dict, -]) -def test_list_report_configs(request_type, transport: str = 'grpc'): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = storageinsights.ListReportConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_report_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.ListReportConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListReportConfigsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_report_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_configs), - '__call__') as call: - client.list_report_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.ListReportConfigsRequest() - -@pytest.mark.asyncio -async def test_list_report_configs_async(transport: str = 'grpc_asyncio', request_type=storageinsights.ListReportConfigsRequest): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ListReportConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_report_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.ListReportConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListReportConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_report_configs_async_from_dict(): - await test_list_report_configs_async(request_type=dict) - - -def test_list_report_configs_field_headers(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = storageinsights.ListReportConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_configs), - '__call__') as call: - call.return_value = storageinsights.ListReportConfigsResponse() - client.list_report_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_report_configs_field_headers_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = storageinsights.ListReportConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ListReportConfigsResponse()) - await client.list_report_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_report_configs_flattened(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = storageinsights.ListReportConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_report_configs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_report_configs_flattened_error(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_report_configs( - storageinsights.ListReportConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_report_configs_flattened_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = storageinsights.ListReportConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ListReportConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_report_configs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_report_configs_flattened_error_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_report_configs( - storageinsights.ListReportConfigsRequest(), - parent='parent_value', - ) - - -def test_list_report_configs_pager(transport_name: str = "grpc"): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - storageinsights.ListReportConfigsResponse( - report_configs=[ - storageinsights.ReportConfig(), - storageinsights.ReportConfig(), - storageinsights.ReportConfig(), - ], - next_page_token='abc', - ), - storageinsights.ListReportConfigsResponse( - report_configs=[], - next_page_token='def', - ), - storageinsights.ListReportConfigsResponse( - report_configs=[ - storageinsights.ReportConfig(), - ], - next_page_token='ghi', - ), - storageinsights.ListReportConfigsResponse( - report_configs=[ - storageinsights.ReportConfig(), - storageinsights.ReportConfig(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_report_configs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, storageinsights.ReportConfig) - for i in results) -def test_list_report_configs_pages(transport_name: str = "grpc"): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - storageinsights.ListReportConfigsResponse( - report_configs=[ - storageinsights.ReportConfig(), - storageinsights.ReportConfig(), - storageinsights.ReportConfig(), - ], - next_page_token='abc', - ), - storageinsights.ListReportConfigsResponse( - report_configs=[], - next_page_token='def', - ), - storageinsights.ListReportConfigsResponse( - report_configs=[ - storageinsights.ReportConfig(), - ], - next_page_token='ghi', - ), - storageinsights.ListReportConfigsResponse( - report_configs=[ - storageinsights.ReportConfig(), - storageinsights.ReportConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_report_configs(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_report_configs_async_pager(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - storageinsights.ListReportConfigsResponse( - report_configs=[ - storageinsights.ReportConfig(), - storageinsights.ReportConfig(), - storageinsights.ReportConfig(), - ], - next_page_token='abc', - ), - storageinsights.ListReportConfigsResponse( - report_configs=[], - next_page_token='def', - ), - storageinsights.ListReportConfigsResponse( - report_configs=[ - storageinsights.ReportConfig(), - ], - next_page_token='ghi', - ), - storageinsights.ListReportConfigsResponse( - report_configs=[ - storageinsights.ReportConfig(), - storageinsights.ReportConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_report_configs(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, storageinsights.ReportConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_report_configs_async_pages(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - storageinsights.ListReportConfigsResponse( - report_configs=[ - storageinsights.ReportConfig(), - storageinsights.ReportConfig(), - storageinsights.ReportConfig(), - ], - next_page_token='abc', - ), - storageinsights.ListReportConfigsResponse( - report_configs=[], - next_page_token='def', - ), - storageinsights.ListReportConfigsResponse( - report_configs=[ - storageinsights.ReportConfig(), - ], - next_page_token='ghi', - ), - storageinsights.ListReportConfigsResponse( - report_configs=[ - storageinsights.ReportConfig(), - storageinsights.ReportConfig(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_report_configs(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - storageinsights.GetReportConfigRequest, - dict, -]) -def test_get_report_config(request_type, transport: str = 'grpc'): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_report_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = storageinsights.ReportConfig( - name='name_value', - display_name='display_name_value', - ) - response = client.get_report_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.GetReportConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, storageinsights.ReportConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_get_report_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = StorageInsightsClient( - credentials=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_report_config), - '__call__') as call: - client.get_report_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.GetReportConfigRequest() - -@pytest.mark.asyncio -async def test_get_report_config_async(transport: str = 'grpc_asyncio', request_type=storageinsights.GetReportConfigRequest): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_report_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportConfig( - name='name_value', - display_name='display_name_value', - )) - response = await client.get_report_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.GetReportConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, storageinsights.ReportConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_get_report_config_async_from_dict(): - await test_get_report_config_async(request_type=dict) - - -def test_get_report_config_field_headers(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = storageinsights.GetReportConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_report_config), - '__call__') as call: - call.return_value = storageinsights.ReportConfig() - client.get_report_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_report_config_field_headers_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = storageinsights.GetReportConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_report_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportConfig()) - await client.get_report_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_report_config_flattened(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_report_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = storageinsights.ReportConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_report_config( - 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_report_config_flattened_error(): - client = StorageInsightsClient( - credentials=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_report_config( - storageinsights.GetReportConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_report_config_flattened_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_report_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = storageinsights.ReportConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_report_config( - 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_report_config_flattened_error_async(): - client = StorageInsightsAsyncClient( - credentials=ga_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_report_config( - storageinsights.GetReportConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - storageinsights.CreateReportConfigRequest, - dict, -]) -def test_create_report_config(request_type, transport: str = 'grpc'): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_report_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = storageinsights.ReportConfig( - name='name_value', - display_name='display_name_value', - ) - response = client.create_report_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.CreateReportConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, storageinsights.ReportConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_create_report_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_report_config), - '__call__') as call: - client.create_report_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.CreateReportConfigRequest() - -@pytest.mark.asyncio -async def test_create_report_config_async(transport: str = 'grpc_asyncio', request_type=storageinsights.CreateReportConfigRequest): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_report_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportConfig( - name='name_value', - display_name='display_name_value', - )) - response = await client.create_report_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.CreateReportConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, storageinsights.ReportConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_create_report_config_async_from_dict(): - await test_create_report_config_async(request_type=dict) - - -def test_create_report_config_field_headers(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = storageinsights.CreateReportConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_report_config), - '__call__') as call: - call.return_value = storageinsights.ReportConfig() - client.create_report_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_report_config_field_headers_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = storageinsights.CreateReportConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_report_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportConfig()) - await client.create_report_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_report_config_flattened(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_report_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = storageinsights.ReportConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_report_config( - parent='parent_value', - report_config=storageinsights.ReportConfig(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].report_config - mock_val = storageinsights.ReportConfig(name='name_value') - assert arg == mock_val - - -def test_create_report_config_flattened_error(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_report_config( - storageinsights.CreateReportConfigRequest(), - parent='parent_value', - report_config=storageinsights.ReportConfig(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_report_config_flattened_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_report_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = storageinsights.ReportConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_report_config( - parent='parent_value', - report_config=storageinsights.ReportConfig(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].report_config - mock_val = storageinsights.ReportConfig(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_report_config_flattened_error_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_report_config( - storageinsights.CreateReportConfigRequest(), - parent='parent_value', - report_config=storageinsights.ReportConfig(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - storageinsights.UpdateReportConfigRequest, - dict, -]) -def test_update_report_config(request_type, transport: str = 'grpc'): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_report_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = storageinsights.ReportConfig( - name='name_value', - display_name='display_name_value', - ) - response = client.update_report_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.UpdateReportConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, storageinsights.ReportConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_update_report_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_report_config), - '__call__') as call: - client.update_report_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.UpdateReportConfigRequest() - -@pytest.mark.asyncio -async def test_update_report_config_async(transport: str = 'grpc_asyncio', request_type=storageinsights.UpdateReportConfigRequest): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_report_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportConfig( - name='name_value', - display_name='display_name_value', - )) - response = await client.update_report_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.UpdateReportConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, storageinsights.ReportConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_update_report_config_async_from_dict(): - await test_update_report_config_async(request_type=dict) - - -def test_update_report_config_field_headers(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = storageinsights.UpdateReportConfigRequest() - - request.report_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_report_config), - '__call__') as call: - call.return_value = storageinsights.ReportConfig() - client.update_report_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'report_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_report_config_field_headers_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = storageinsights.UpdateReportConfigRequest() - - request.report_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_report_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportConfig()) - await client.update_report_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'report_config.name=name_value', - ) in kw['metadata'] - - -def test_update_report_config_flattened(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_report_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = storageinsights.ReportConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_report_config( - report_config=storageinsights.ReportConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].report_config - mock_val = storageinsights.ReportConfig(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_report_config_flattened_error(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_report_config( - storageinsights.UpdateReportConfigRequest(), - report_config=storageinsights.ReportConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_report_config_flattened_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_report_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = storageinsights.ReportConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_report_config( - report_config=storageinsights.ReportConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].report_config - mock_val = storageinsights.ReportConfig(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_report_config_flattened_error_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_report_config( - storageinsights.UpdateReportConfigRequest(), - report_config=storageinsights.ReportConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - storageinsights.DeleteReportConfigRequest, - dict, -]) -def test_delete_report_config(request_type, transport: str = 'grpc'): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_report_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_report_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.DeleteReportConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_report_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_report_config), - '__call__') as call: - client.delete_report_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.DeleteReportConfigRequest() - -@pytest.mark.asyncio -async def test_delete_report_config_async(transport: str = 'grpc_asyncio', request_type=storageinsights.DeleteReportConfigRequest): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_report_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_report_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.DeleteReportConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_report_config_async_from_dict(): - await test_delete_report_config_async(request_type=dict) - - -def test_delete_report_config_field_headers(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = storageinsights.DeleteReportConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_report_config), - '__call__') as call: - call.return_value = None - client.delete_report_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_report_config_field_headers_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = storageinsights.DeleteReportConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_report_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_report_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_report_config_flattened(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_report_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_report_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_report_config_flattened_error(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_report_config( - storageinsights.DeleteReportConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_report_config_flattened_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_report_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_report_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_report_config_flattened_error_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_report_config( - storageinsights.DeleteReportConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - storageinsights.ListReportDetailsRequest, - dict, -]) -def test_list_report_details(request_type, transport: str = 'grpc'): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_details), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = storageinsights.ListReportDetailsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_report_details(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.ListReportDetailsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListReportDetailsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_report_details_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_details), - '__call__') as call: - client.list_report_details() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.ListReportDetailsRequest() - -@pytest.mark.asyncio -async def test_list_report_details_async(transport: str = 'grpc_asyncio', request_type=storageinsights.ListReportDetailsRequest): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_details), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ListReportDetailsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_report_details(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.ListReportDetailsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListReportDetailsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_report_details_async_from_dict(): - await test_list_report_details_async(request_type=dict) - - -def test_list_report_details_field_headers(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = storageinsights.ListReportDetailsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_details), - '__call__') as call: - call.return_value = storageinsights.ListReportDetailsResponse() - client.list_report_details(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_report_details_field_headers_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = storageinsights.ListReportDetailsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_details), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ListReportDetailsResponse()) - await client.list_report_details(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_report_details_flattened(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_details), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = storageinsights.ListReportDetailsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_report_details( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_report_details_flattened_error(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_report_details( - storageinsights.ListReportDetailsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_report_details_flattened_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_details), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = storageinsights.ListReportDetailsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ListReportDetailsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_report_details( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_report_details_flattened_error_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_report_details( - storageinsights.ListReportDetailsRequest(), - parent='parent_value', - ) - - -def test_list_report_details_pager(transport_name: str = "grpc"): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_details), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - storageinsights.ListReportDetailsResponse( - report_details=[ - storageinsights.ReportDetail(), - storageinsights.ReportDetail(), - storageinsights.ReportDetail(), - ], - next_page_token='abc', - ), - storageinsights.ListReportDetailsResponse( - report_details=[], - next_page_token='def', - ), - storageinsights.ListReportDetailsResponse( - report_details=[ - storageinsights.ReportDetail(), - ], - next_page_token='ghi', - ), - storageinsights.ListReportDetailsResponse( - report_details=[ - storageinsights.ReportDetail(), - storageinsights.ReportDetail(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_report_details(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, storageinsights.ReportDetail) - for i in results) -def test_list_report_details_pages(transport_name: str = "grpc"): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_details), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - storageinsights.ListReportDetailsResponse( - report_details=[ - storageinsights.ReportDetail(), - storageinsights.ReportDetail(), - storageinsights.ReportDetail(), - ], - next_page_token='abc', - ), - storageinsights.ListReportDetailsResponse( - report_details=[], - next_page_token='def', - ), - storageinsights.ListReportDetailsResponse( - report_details=[ - storageinsights.ReportDetail(), - ], - next_page_token='ghi', - ), - storageinsights.ListReportDetailsResponse( - report_details=[ - storageinsights.ReportDetail(), - storageinsights.ReportDetail(), - ], - ), - RuntimeError, - ) - pages = list(client.list_report_details(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_report_details_async_pager(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_details), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - storageinsights.ListReportDetailsResponse( - report_details=[ - storageinsights.ReportDetail(), - storageinsights.ReportDetail(), - storageinsights.ReportDetail(), - ], - next_page_token='abc', - ), - storageinsights.ListReportDetailsResponse( - report_details=[], - next_page_token='def', - ), - storageinsights.ListReportDetailsResponse( - report_details=[ - storageinsights.ReportDetail(), - ], - next_page_token='ghi', - ), - storageinsights.ListReportDetailsResponse( - report_details=[ - storageinsights.ReportDetail(), - storageinsights.ReportDetail(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_report_details(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, storageinsights.ReportDetail) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_report_details_async_pages(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_report_details), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - storageinsights.ListReportDetailsResponse( - report_details=[ - storageinsights.ReportDetail(), - storageinsights.ReportDetail(), - storageinsights.ReportDetail(), - ], - next_page_token='abc', - ), - storageinsights.ListReportDetailsResponse( - report_details=[], - next_page_token='def', - ), - storageinsights.ListReportDetailsResponse( - report_details=[ - storageinsights.ReportDetail(), - ], - next_page_token='ghi', - ), - storageinsights.ListReportDetailsResponse( - report_details=[ - storageinsights.ReportDetail(), - storageinsights.ReportDetail(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_report_details(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - storageinsights.GetReportDetailRequest, - dict, -]) -def test_get_report_detail(request_type, transport: str = 'grpc'): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_report_detail), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = storageinsights.ReportDetail( - name='name_value', - report_path_prefix='report_path_prefix_value', - shards_count=1293, - ) - response = client.get_report_detail(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.GetReportDetailRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, storageinsights.ReportDetail) - assert response.name == 'name_value' - assert response.report_path_prefix == 'report_path_prefix_value' - assert response.shards_count == 1293 - - -def test_get_report_detail_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = StorageInsightsClient( - credentials=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_report_detail), - '__call__') as call: - client.get_report_detail() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.GetReportDetailRequest() - -@pytest.mark.asyncio -async def test_get_report_detail_async(transport: str = 'grpc_asyncio', request_type=storageinsights.GetReportDetailRequest): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_report_detail), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportDetail( - name='name_value', - report_path_prefix='report_path_prefix_value', - shards_count=1293, - )) - response = await client.get_report_detail(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == storageinsights.GetReportDetailRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, storageinsights.ReportDetail) - assert response.name == 'name_value' - assert response.report_path_prefix == 'report_path_prefix_value' - assert response.shards_count == 1293 - - -@pytest.mark.asyncio -async def test_get_report_detail_async_from_dict(): - await test_get_report_detail_async(request_type=dict) - - -def test_get_report_detail_field_headers(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = storageinsights.GetReportDetailRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_report_detail), - '__call__') as call: - call.return_value = storageinsights.ReportDetail() - client.get_report_detail(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_report_detail_field_headers_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = storageinsights.GetReportDetailRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_report_detail), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportDetail()) - await client.get_report_detail(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_report_detail_flattened(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_report_detail), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = storageinsights.ReportDetail() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_report_detail( - 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_report_detail_flattened_error(): - client = StorageInsightsClient( - credentials=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_report_detail( - storageinsights.GetReportDetailRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_report_detail_flattened_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_report_detail), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = storageinsights.ReportDetail() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(storageinsights.ReportDetail()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_report_detail( - 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_report_detail_flattened_error_async(): - client = StorageInsightsAsyncClient( - credentials=ga_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_report_detail( - storageinsights.GetReportDetailRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - storageinsights.ListReportConfigsRequest, - dict, -]) -def test_list_report_configs_rest(request_type): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = storageinsights.ListReportConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = storageinsights.ListReportConfigsResponse.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.list_report_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListReportConfigsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_report_configs_rest_required_fields(request_type=storageinsights.ListReportConfigsRequest): - transport_class = transports.StorageInsightsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - 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()).list_report_configs._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_report_configs._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = storageinsights.ListReportConfigsResponse() - # 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 = storageinsights.ListReportConfigsResponse.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.list_report_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_report_configs_rest_unset_required_fields(): - transport = transports.StorageInsightsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_report_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_report_configs_rest_interceptors(null_interceptor): - transport = transports.StorageInsightsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.StorageInsightsRestInterceptor(), - ) - client = StorageInsightsClient(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.StorageInsightsRestInterceptor, "post_list_report_configs") as post, \ - mock.patch.object(transports.StorageInsightsRestInterceptor, "pre_list_report_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = storageinsights.ListReportConfigsRequest.pb(storageinsights.ListReportConfigsRequest()) - 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 = storageinsights.ListReportConfigsResponse.to_json(storageinsights.ListReportConfigsResponse()) - - request = storageinsights.ListReportConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = storageinsights.ListReportConfigsResponse() - - client.list_report_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_report_configs_rest_bad_request(transport: str = 'rest', request_type=storageinsights.ListReportConfigsRequest): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_report_configs(request) - - -def test_list_report_configs_rest_flattened(): - client = StorageInsightsClient( - 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 = storageinsights.ListReportConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = storageinsights.ListReportConfigsResponse.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.list_report_configs(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/reportConfigs" % client.transport._host, args[1]) - - -def test_list_report_configs_rest_flattened_error(transport: str = 'rest'): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_report_configs( - storageinsights.ListReportConfigsRequest(), - parent='parent_value', - ) - - -def test_list_report_configs_rest_pager(transport: str = 'rest'): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - storageinsights.ListReportConfigsResponse( - report_configs=[ - storageinsights.ReportConfig(), - storageinsights.ReportConfig(), - storageinsights.ReportConfig(), - ], - next_page_token='abc', - ), - storageinsights.ListReportConfigsResponse( - report_configs=[], - next_page_token='def', - ), - storageinsights.ListReportConfigsResponse( - report_configs=[ - storageinsights.ReportConfig(), - ], - next_page_token='ghi', - ), - storageinsights.ListReportConfigsResponse( - report_configs=[ - storageinsights.ReportConfig(), - storageinsights.ReportConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(storageinsights.ListReportConfigsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_report_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, storageinsights.ReportConfig) - for i in results) - - pages = list(client.list_report_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - storageinsights.GetReportConfigRequest, - dict, -]) -def test_get_report_config_rest(request_type): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = storageinsights.ReportConfig( - name='name_value', - display_name='display_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = storageinsights.ReportConfig.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_report_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, storageinsights.ReportConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_get_report_config_rest_required_fields(request_type=storageinsights.GetReportConfigRequest): - transport_class = transports.StorageInsightsRestTransport - - 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_report_config._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_report_config._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 = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = storageinsights.ReportConfig() - # 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 = storageinsights.ReportConfig.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_report_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_report_config_rest_unset_required_fields(): - transport = transports.StorageInsightsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_report_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_report_config_rest_interceptors(null_interceptor): - transport = transports.StorageInsightsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.StorageInsightsRestInterceptor(), - ) - client = StorageInsightsClient(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.StorageInsightsRestInterceptor, "post_get_report_config") as post, \ - mock.patch.object(transports.StorageInsightsRestInterceptor, "pre_get_report_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = storageinsights.GetReportConfigRequest.pb(storageinsights.GetReportConfigRequest()) - 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 = storageinsights.ReportConfig.to_json(storageinsights.ReportConfig()) - - request = storageinsights.GetReportConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = storageinsights.ReportConfig() - - client.get_report_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_report_config_rest_bad_request(transport: str = 'rest', request_type=storageinsights.GetReportConfigRequest): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_report_config(request) - - -def test_get_report_config_rest_flattened(): - client = StorageInsightsClient( - 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 = storageinsights.ReportConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = storageinsights.ReportConfig.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_report_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/reportConfigs/*}" % client.transport._host, args[1]) - - -def test_get_report_config_rest_flattened_error(transport: str = 'rest'): - client = StorageInsightsClient( - 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_report_config( - storageinsights.GetReportConfigRequest(), - name='name_value', - ) - - -def test_get_report_config_rest_error(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - storageinsights.CreateReportConfigRequest, - dict, -]) -def test_create_report_config_rest(request_type): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["report_config"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'frequency_options': {'frequency': 1, 'start_date': {'year': 433, 'month': 550, 'day': 318}, 'end_date': {}}, 'csv_options': {'record_separator': 'record_separator_value', 'delimiter': 'delimiter_value', 'header_required': True}, 'parquet_options': {}, 'object_metadata_report_options': {'metadata_fields': ['metadata_fields_value1', 'metadata_fields_value2'], 'storage_filters': {'bucket': 'bucket_value'}, 'storage_destination_options': {'bucket': 'bucket_value', 'destination_path': 'destination_path_value'}}, 'labels': {}, 'display_name': 'display_name_value'} - 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 = storageinsights.ReportConfig( - name='name_value', - display_name='display_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = storageinsights.ReportConfig.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.create_report_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, storageinsights.ReportConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_create_report_config_rest_required_fields(request_type=storageinsights.CreateReportConfigRequest): - transport_class = transports.StorageInsightsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - 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()).create_report_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_report_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = storageinsights.ReportConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = storageinsights.ReportConfig.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.create_report_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_report_config_rest_unset_required_fields(): - transport = transports.StorageInsightsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_report_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId", )) & set(("parent", "reportConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_report_config_rest_interceptors(null_interceptor): - transport = transports.StorageInsightsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.StorageInsightsRestInterceptor(), - ) - client = StorageInsightsClient(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.StorageInsightsRestInterceptor, "post_create_report_config") as post, \ - mock.patch.object(transports.StorageInsightsRestInterceptor, "pre_create_report_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = storageinsights.CreateReportConfigRequest.pb(storageinsights.CreateReportConfigRequest()) - 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 = storageinsights.ReportConfig.to_json(storageinsights.ReportConfig()) - - request = storageinsights.CreateReportConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = storageinsights.ReportConfig() - - client.create_report_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_report_config_rest_bad_request(transport: str = 'rest', request_type=storageinsights.CreateReportConfigRequest): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["report_config"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'frequency_options': {'frequency': 1, 'start_date': {'year': 433, 'month': 550, 'day': 318}, 'end_date': {}}, 'csv_options': {'record_separator': 'record_separator_value', 'delimiter': 'delimiter_value', 'header_required': True}, 'parquet_options': {}, 'object_metadata_report_options': {'metadata_fields': ['metadata_fields_value1', 'metadata_fields_value2'], 'storage_filters': {'bucket': 'bucket_value'}, 'storage_destination_options': {'bucket': 'bucket_value', 'destination_path': 'destination_path_value'}}, 'labels': {}, 'display_name': 'display_name_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_report_config(request) - - -def test_create_report_config_rest_flattened(): - client = StorageInsightsClient( - 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 = storageinsights.ReportConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - report_config=storageinsights.ReportConfig(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 = storageinsights.ReportConfig.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.create_report_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/reportConfigs" % client.transport._host, args[1]) - - -def test_create_report_config_rest_flattened_error(transport: str = 'rest'): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_report_config( - storageinsights.CreateReportConfigRequest(), - parent='parent_value', - report_config=storageinsights.ReportConfig(name='name_value'), - ) - - -def test_create_report_config_rest_error(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - storageinsights.UpdateReportConfigRequest, - dict, -]) -def test_update_report_config_rest(request_type): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'report_config': {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3'}} - request_init["report_config"] = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'frequency_options': {'frequency': 1, 'start_date': {'year': 433, 'month': 550, 'day': 318}, 'end_date': {}}, 'csv_options': {'record_separator': 'record_separator_value', 'delimiter': 'delimiter_value', 'header_required': True}, 'parquet_options': {}, 'object_metadata_report_options': {'metadata_fields': ['metadata_fields_value1', 'metadata_fields_value2'], 'storage_filters': {'bucket': 'bucket_value'}, 'storage_destination_options': {'bucket': 'bucket_value', 'destination_path': 'destination_path_value'}}, 'labels': {}, 'display_name': 'display_name_value'} - 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 = storageinsights.ReportConfig( - name='name_value', - display_name='display_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = storageinsights.ReportConfig.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.update_report_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, storageinsights.ReportConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_update_report_config_rest_required_fields(request_type=storageinsights.UpdateReportConfigRequest): - transport_class = transports.StorageInsightsRestTransport - - request_init = {} - 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()).update_report_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_report_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = storageinsights.ReportConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = storageinsights.ReportConfig.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.update_report_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_report_config_rest_unset_required_fields(): - transport = transports.StorageInsightsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_report_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "reportConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_report_config_rest_interceptors(null_interceptor): - transport = transports.StorageInsightsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.StorageInsightsRestInterceptor(), - ) - client = StorageInsightsClient(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.StorageInsightsRestInterceptor, "post_update_report_config") as post, \ - mock.patch.object(transports.StorageInsightsRestInterceptor, "pre_update_report_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = storageinsights.UpdateReportConfigRequest.pb(storageinsights.UpdateReportConfigRequest()) - 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 = storageinsights.ReportConfig.to_json(storageinsights.ReportConfig()) - - request = storageinsights.UpdateReportConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = storageinsights.ReportConfig() - - client.update_report_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_report_config_rest_bad_request(transport: str = 'rest', request_type=storageinsights.UpdateReportConfigRequest): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'report_config': {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3'}} - request_init["report_config"] = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'frequency_options': {'frequency': 1, 'start_date': {'year': 433, 'month': 550, 'day': 318}, 'end_date': {}}, 'csv_options': {'record_separator': 'record_separator_value', 'delimiter': 'delimiter_value', 'header_required': True}, 'parquet_options': {}, 'object_metadata_report_options': {'metadata_fields': ['metadata_fields_value1', 'metadata_fields_value2'], 'storage_filters': {'bucket': 'bucket_value'}, 'storage_destination_options': {'bucket': 'bucket_value', 'destination_path': 'destination_path_value'}}, 'labels': {}, 'display_name': 'display_name_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_report_config(request) - - -def test_update_report_config_rest_flattened(): - client = StorageInsightsClient( - 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 = storageinsights.ReportConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'report_config': {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - report_config=storageinsights.ReportConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = storageinsights.ReportConfig.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.update_report_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{report_config.name=projects/*/locations/*/reportConfigs/*}" % client.transport._host, args[1]) - - -def test_update_report_config_rest_flattened_error(transport: str = 'rest'): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_report_config( - storageinsights.UpdateReportConfigRequest(), - report_config=storageinsights.ReportConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_report_config_rest_error(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - storageinsights.DeleteReportConfigRequest, - dict, -]) -def test_delete_report_config_rest(request_type): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_report_config(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_report_config_rest_required_fields(request_type=storageinsights.DeleteReportConfigRequest): - transport_class = transports.StorageInsightsRestTransport - - 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()).delete_report_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_report_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("force", "request_id", )) - 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 = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_report_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_report_config_rest_unset_required_fields(): - transport = transports.StorageInsightsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_report_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("force", "requestId", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_report_config_rest_interceptors(null_interceptor): - transport = transports.StorageInsightsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.StorageInsightsRestInterceptor(), - ) - client = StorageInsightsClient(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.StorageInsightsRestInterceptor, "pre_delete_report_config") as pre: - pre.assert_not_called() - pb_message = storageinsights.DeleteReportConfigRequest.pb(storageinsights.DeleteReportConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = storageinsights.DeleteReportConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_report_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_report_config_rest_bad_request(transport: str = 'rest', request_type=storageinsights.DeleteReportConfigRequest): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_report_config(request) - - -def test_delete_report_config_rest_flattened(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_report_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/reportConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_report_config_rest_flattened_error(transport: str = 'rest'): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_report_config( - storageinsights.DeleteReportConfigRequest(), - name='name_value', - ) - - -def test_delete_report_config_rest_error(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - storageinsights.ListReportDetailsRequest, - dict, -]) -def test_list_report_details_rest(request_type): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/reportConfigs/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = storageinsights.ListReportDetailsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = storageinsights.ListReportDetailsResponse.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.list_report_details(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListReportDetailsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_report_details_rest_required_fields(request_type=storageinsights.ListReportDetailsRequest): - transport_class = transports.StorageInsightsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - 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()).list_report_details._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_report_details._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = storageinsights.ListReportDetailsResponse() - # 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 = storageinsights.ListReportDetailsResponse.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.list_report_details(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_report_details_rest_unset_required_fields(): - transport = transports.StorageInsightsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_report_details._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_report_details_rest_interceptors(null_interceptor): - transport = transports.StorageInsightsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.StorageInsightsRestInterceptor(), - ) - client = StorageInsightsClient(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.StorageInsightsRestInterceptor, "post_list_report_details") as post, \ - mock.patch.object(transports.StorageInsightsRestInterceptor, "pre_list_report_details") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = storageinsights.ListReportDetailsRequest.pb(storageinsights.ListReportDetailsRequest()) - 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 = storageinsights.ListReportDetailsResponse.to_json(storageinsights.ListReportDetailsResponse()) - - request = storageinsights.ListReportDetailsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = storageinsights.ListReportDetailsResponse() - - client.list_report_details(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_report_details_rest_bad_request(transport: str = 'rest', request_type=storageinsights.ListReportDetailsRequest): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/reportConfigs/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_report_details(request) - - -def test_list_report_details_rest_flattened(): - client = StorageInsightsClient( - 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 = storageinsights.ListReportDetailsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/reportConfigs/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = storageinsights.ListReportDetailsResponse.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.list_report_details(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/reportConfigs/*}/reportDetails" % client.transport._host, args[1]) - - -def test_list_report_details_rest_flattened_error(transport: str = 'rest'): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_report_details( - storageinsights.ListReportDetailsRequest(), - parent='parent_value', - ) - - -def test_list_report_details_rest_pager(transport: str = 'rest'): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - storageinsights.ListReportDetailsResponse( - report_details=[ - storageinsights.ReportDetail(), - storageinsights.ReportDetail(), - storageinsights.ReportDetail(), - ], - next_page_token='abc', - ), - storageinsights.ListReportDetailsResponse( - report_details=[], - next_page_token='def', - ), - storageinsights.ListReportDetailsResponse( - report_details=[ - storageinsights.ReportDetail(), - ], - next_page_token='ghi', - ), - storageinsights.ListReportDetailsResponse( - report_details=[ - storageinsights.ReportDetail(), - storageinsights.ReportDetail(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(storageinsights.ListReportDetailsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/reportConfigs/sample3'} - - pager = client.list_report_details(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, storageinsights.ReportDetail) - for i in results) - - pages = list(client.list_report_details(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - storageinsights.GetReportDetailRequest, - dict, -]) -def test_get_report_detail_rest(request_type): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3/reportDetails/sample4'} - 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 = storageinsights.ReportDetail( - name='name_value', - report_path_prefix='report_path_prefix_value', - shards_count=1293, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = storageinsights.ReportDetail.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_report_detail(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, storageinsights.ReportDetail) - assert response.name == 'name_value' - assert response.report_path_prefix == 'report_path_prefix_value' - assert response.shards_count == 1293 - - -def test_get_report_detail_rest_required_fields(request_type=storageinsights.GetReportDetailRequest): - transport_class = transports.StorageInsightsRestTransport - - 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_report_detail._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_report_detail._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 = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = storageinsights.ReportDetail() - # 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 = storageinsights.ReportDetail.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_report_detail(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_report_detail_rest_unset_required_fields(): - transport = transports.StorageInsightsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_report_detail._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_report_detail_rest_interceptors(null_interceptor): - transport = transports.StorageInsightsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.StorageInsightsRestInterceptor(), - ) - client = StorageInsightsClient(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.StorageInsightsRestInterceptor, "post_get_report_detail") as post, \ - mock.patch.object(transports.StorageInsightsRestInterceptor, "pre_get_report_detail") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = storageinsights.GetReportDetailRequest.pb(storageinsights.GetReportDetailRequest()) - 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 = storageinsights.ReportDetail.to_json(storageinsights.ReportDetail()) - - request = storageinsights.GetReportDetailRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = storageinsights.ReportDetail() - - client.get_report_detail(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_report_detail_rest_bad_request(transport: str = 'rest', request_type=storageinsights.GetReportDetailRequest): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3/reportDetails/sample4'} - 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_report_detail(request) - - -def test_get_report_detail_rest_flattened(): - client = StorageInsightsClient( - 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 = storageinsights.ReportDetail() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/reportConfigs/sample3/reportDetails/sample4'} - - # 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 = storageinsights.ReportDetail.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_report_detail(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/reportConfigs/*/reportDetails/*}" % client.transport._host, args[1]) - - -def test_get_report_detail_rest_flattened_error(transport: str = 'rest'): - client = StorageInsightsClient( - 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_report_detail( - storageinsights.GetReportDetailRequest(), - name='name_value', - ) - - -def test_get_report_detail_rest_error(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.StorageInsightsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.StorageInsightsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = StorageInsightsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.StorageInsightsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = StorageInsightsClient( - 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 = StorageInsightsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.StorageInsightsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = StorageInsightsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.StorageInsightsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = StorageInsightsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.StorageInsightsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.StorageInsightsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.StorageInsightsGrpcTransport, - transports.StorageInsightsGrpcAsyncIOTransport, - transports.StorageInsightsRestTransport, -]) -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 = StorageInsightsClient.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 = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.StorageInsightsGrpcTransport, - ) - -def test_storage_insights_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.StorageInsightsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_storage_insights_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.storageinsights_v1.services.storage_insights.transports.StorageInsightsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.StorageInsightsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_report_configs', - 'get_report_config', - 'create_report_config', - 'update_report_config', - 'delete_report_config', - 'list_report_details', - 'get_report_detail', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'delete_operation', - 'list_operations', - ) - 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_storage_insights_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.storageinsights_v1.services.storage_insights.transports.StorageInsightsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.StorageInsightsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_storage_insights_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.storageinsights_v1.services.storage_insights.transports.StorageInsightsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.StorageInsightsTransport() - adc.assert_called_once() - - -def test_storage_insights_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) - StorageInsightsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.StorageInsightsGrpcTransport, - transports.StorageInsightsGrpcAsyncIOTransport, - ], -) -def test_storage_insights_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.StorageInsightsGrpcTransport, - transports.StorageInsightsGrpcAsyncIOTransport, - transports.StorageInsightsRestTransport, - ], -) -def test_storage_insights_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.StorageInsightsGrpcTransport, grpc_helpers), - (transports.StorageInsightsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_storage_insights_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( - "storageinsights.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="storageinsights.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.StorageInsightsGrpcTransport, transports.StorageInsightsGrpcAsyncIOTransport]) -def test_storage_insights_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_storage_insights_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.StorageInsightsRestTransport ( - 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_storage_insights_host_no_port(transport_name): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='storageinsights.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'storageinsights.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://storageinsights.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_storage_insights_host_with_port(transport_name): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='storageinsights.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'storageinsights.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://storageinsights.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_storage_insights_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = StorageInsightsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = StorageInsightsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_report_configs._session - session2 = client2.transport.list_report_configs._session - assert session1 != session2 - session1 = client1.transport.get_report_config._session - session2 = client2.transport.get_report_config._session - assert session1 != session2 - session1 = client1.transport.create_report_config._session - session2 = client2.transport.create_report_config._session - assert session1 != session2 - session1 = client1.transport.update_report_config._session - session2 = client2.transport.update_report_config._session - assert session1 != session2 - session1 = client1.transport.delete_report_config._session - session2 = client2.transport.delete_report_config._session - assert session1 != session2 - session1 = client1.transport.list_report_details._session - session2 = client2.transport.list_report_details._session - assert session1 != session2 - session1 = client1.transport.get_report_detail._session - session2 = client2.transport.get_report_detail._session - assert session1 != session2 -def test_storage_insights_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.StorageInsightsGrpcTransport( - 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_storage_insights_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.StorageInsightsGrpcAsyncIOTransport( - 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.StorageInsightsGrpcTransport, transports.StorageInsightsGrpcAsyncIOTransport]) -def test_storage_insights_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.StorageInsightsGrpcTransport, transports.StorageInsightsGrpcAsyncIOTransport]) -def test_storage_insights_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_report_config_path(): - project = "squid" - location = "clam" - report_config = "whelk" - expected = "projects/{project}/locations/{location}/reportConfigs/{report_config}".format(project=project, location=location, report_config=report_config, ) - actual = StorageInsightsClient.report_config_path(project, location, report_config) - assert expected == actual - - -def test_parse_report_config_path(): - expected = { - "project": "octopus", - "location": "oyster", - "report_config": "nudibranch", - } - path = StorageInsightsClient.report_config_path(**expected) - - # Check that the path construction is reversible. - actual = StorageInsightsClient.parse_report_config_path(path) - assert expected == actual - -def test_report_detail_path(): - project = "cuttlefish" - location = "mussel" - report_config = "winkle" - report_detail = "nautilus" - expected = "projects/{project}/locations/{location}/reportConfigs/{report_config}/reportDetails/{report_detail}".format(project=project, location=location, report_config=report_config, report_detail=report_detail, ) - actual = StorageInsightsClient.report_detail_path(project, location, report_config, report_detail) - assert expected == actual - - -def test_parse_report_detail_path(): - expected = { - "project": "scallop", - "location": "abalone", - "report_config": "squid", - "report_detail": "clam", - } - path = StorageInsightsClient.report_detail_path(**expected) - - # Check that the path construction is reversible. - actual = StorageInsightsClient.parse_report_detail_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = StorageInsightsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = StorageInsightsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = StorageInsightsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = StorageInsightsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = StorageInsightsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = StorageInsightsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = StorageInsightsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = StorageInsightsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = StorageInsightsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = StorageInsightsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = StorageInsightsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = StorageInsightsClient.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 = StorageInsightsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = StorageInsightsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = StorageInsightsClient.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.StorageInsightsTransport, '_prep_wrapped_messages') as prep: - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.StorageInsightsTransport, '_prep_wrapped_messages') as prep: - transport_class = StorageInsightsClient.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 = StorageInsightsAsyncClient( - 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_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # 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_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/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 = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # 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_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_delete_operation(transport: str = "grpc"): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_delete_operation_async(transport: str = "grpc"): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_operation_field_headers(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = None - - client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_delete_operation_field_headers_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_delete_operation_from_dict(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_delete_operation_from_dict_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_cancel_operation(transport: str = "grpc"): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials() - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = StorageInsightsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = StorageInsightsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = StorageInsightsClient( - 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 = StorageInsightsClient( - 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", [ - (StorageInsightsClient, transports.StorageInsightsGrpcTransport), - (StorageInsightsAsyncClient, transports.StorageInsightsGrpcAsyncIOTransport), -]) -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/packages/google-cloud-storageinsights/.flake8 b/packages/google-cloud-storageinsights/.flake8 index 2e438749863d..87f6e408c47d 100644 --- a/packages/google-cloud-storageinsights/.flake8 +++ b/packages/google-cloud-storageinsights/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2020 Google LLC +# Copyright 2023 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-storageinsights/CONTRIBUTING.rst b/packages/google-cloud-storageinsights/CONTRIBUTING.rst index f3e4a3b25dd0..d927e564e6cc 100644 --- a/packages/google-cloud-storageinsights/CONTRIBUTING.rst +++ b/packages/google-cloud-storageinsights/CONTRIBUTING.rst @@ -236,7 +236,7 @@ We support: Supported versions can be found in our ``noxfile.py`` `config`_. -.. _config: https://github.com/googleapis/google-cloud-python/blob/main/noxfile.py +.. _config: https://github.com/googleapis/google-cloud-python/blob/main/packages/google-cloud-storageinsights/noxfile.py ********** diff --git a/packages/google-cloud-storageinsights/MANIFEST.in b/packages/google-cloud-storageinsights/MANIFEST.in index e783f4c6209b..e0a66705318e 100644 --- a/packages/google-cloud-storageinsights/MANIFEST.in +++ b/packages/google-cloud-storageinsights/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2020 Google LLC +# Copyright 2023 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-storageinsights/README.rst b/packages/google-cloud-storageinsights/README.rst index 3284b672ca72..ebde0b0f6c7c 100644 --- a/packages/google-cloud-storageinsights/README.rst +++ b/packages/google-cloud-storageinsights/README.rst @@ -36,21 +36,24 @@ In order to use this library, you first need to go through the following steps: 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. +Install this library in a virtual environment using `venv`_. `venv`_ is a tool that +creates isolated Python environments. These isolated environments can have separate +versions of Python packages, which allows you to isolate one project's dependencies +from the dependencies of other projects. -With `virtualenv`_, it's possible to install this library without needing system +With `venv`_, 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/ +.. _`venv`: https://docs.python.org/3/library/venv.html Code samples and snippets ~~~~~~~~~~~~~~~~~~~~~~~~~ -Code samples and snippets live in the `samples/` folder. +Code samples and snippets live in the `samples/`_ folder. + +.. _samples/: https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storageinsights/samples Supported Python Versions @@ -77,10 +80,9 @@ Mac/Linux .. code-block:: console - pip install virtualenv - virtualenv + python3 -m venv source /bin/activate - /bin/pip install google-cloud-storageinsights + pip install google-cloud-storageinsights Windows @@ -88,10 +90,9 @@ Windows .. code-block:: console - pip install virtualenv - virtualenv - \Scripts\activate - \Scripts\pip.exe install google-cloud-storageinsights + py -m venv + .\\Scripts\activate + pip install google-cloud-storageinsights Next Steps ~~~~~~~~~~ diff --git a/packages/google-cloud-storageinsights/docs/conf.py b/packages/google-cloud-storageinsights/docs/conf.py index 70313b92df82..994366fb446f 100644 --- a/packages/google-cloud-storageinsights/docs/conf.py +++ b/packages/google-cloud-storageinsights/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2021 Google LLC +# Copyright 2023 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/services/storage_insights/async_client.py b/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/services/storage_insights/async_client.py index 5b62d6471656..a1691de71889 100644 --- a/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/services/storage_insights/async_client.py +++ b/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/services/storage_insights/async_client.py @@ -406,8 +406,10 @@ async def sample_get_report_config(): google.cloud.storageinsights_v1.types.ReportConfig: Message describing ReportConfig object. ReportConfig is the - configuration to generate reports. Next - ID: 12 + configuration to generate reports. See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various + fields. Next ID: 12 """ # Create or coerce a protobuf request object. @@ -525,8 +527,10 @@ async def sample_create_report_config(): google.cloud.storageinsights_v1.types.ReportConfig: Message describing ReportConfig object. ReportConfig is the - configuration to generate reports. Next - ID: 12 + configuration to generate reports. See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various + fields. Next ID: 12 """ # Create or coerce a protobuf request object. @@ -641,8 +645,10 @@ async def sample_update_report_config(): google.cloud.storageinsights_v1.types.ReportConfig: Message describing ReportConfig object. ReportConfig is the - configuration to generate reports. Next - ID: 12 + configuration to generate reports. See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various + fields. Next ID: 12 """ # Create or coerce a protobuf request object. diff --git a/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/services/storage_insights/client.py b/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/services/storage_insights/client.py index 9c530a20a513..cbf8e4f7d2d7 100644 --- a/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/services/storage_insights/client.py +++ b/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/services/storage_insights/client.py @@ -644,8 +644,10 @@ def sample_get_report_config(): google.cloud.storageinsights_v1.types.ReportConfig: Message describing ReportConfig object. ReportConfig is the - configuration to generate reports. Next - ID: 12 + configuration to generate reports. See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various + fields. Next ID: 12 """ # Create or coerce a protobuf request object. @@ -754,8 +756,10 @@ def sample_create_report_config(): google.cloud.storageinsights_v1.types.ReportConfig: Message describing ReportConfig object. ReportConfig is the - configuration to generate reports. Next - ID: 12 + configuration to generate reports. See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various + fields. Next ID: 12 """ # Create or coerce a protobuf request object. @@ -870,8 +874,10 @@ def sample_update_report_config(): google.cloud.storageinsights_v1.types.ReportConfig: Message describing ReportConfig object. ReportConfig is the - configuration to generate reports. Next - ID: 12 + configuration to generate reports. See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various + fields. Next ID: 12 """ # Create or coerce a protobuf request object. diff --git a/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/services/storage_insights/transports/rest.py b/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/services/storage_insights/transports/rest.py index 668b127d4d99..c2d381be12f3 100644 --- a/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/services/storage_insights/transports/rest.py +++ b/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/services/storage_insights/transports/rest.py @@ -543,8 +543,10 @@ def __call__( ~.storageinsights.ReportConfig: Message describing ReportConfig object. ReportConfig is the - configuration to generate reports. Next - ID: 12 + configuration to generate reports. See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various + fields. Next ID: 12 """ @@ -720,8 +722,10 @@ def __call__( ~.storageinsights.ReportConfig: Message describing ReportConfig object. ReportConfig is the - configuration to generate reports. Next - ID: 12 + configuration to generate reports. See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various + fields. Next ID: 12 """ @@ -1088,8 +1092,10 @@ def __call__( ~.storageinsights.ReportConfig: Message describing ReportConfig object. ReportConfig is the - configuration to generate reports. Next - ID: 12 + configuration to generate reports. See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various + fields. Next ID: 12 """ diff --git a/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/types/storageinsights.py b/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/types/storageinsights.py index 01cf5f9958e4..b23b0e02618f 100644 --- a/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/types/storageinsights.py +++ b/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/types/storageinsights.py @@ -670,6 +670,9 @@ class ObjectMetadataReportOptions(proto.Message): class ReportConfig(proto.Message): r"""Message describing ReportConfig object. ReportConfig is the configuration to generate reports. + See + https://cloud.google.com/storage/docs/insights/using-inventory-reports#create-config-rest + for more details on how to set various fields. Next ID: 12 This message has `oneof`_ fields (mutually exclusive fields). diff --git a/packages/google-cloud-storageinsights/noxfile.py b/packages/google-cloud-storageinsights/noxfile.py index 6f5debd52f23..9a2acd8b6787 100644 --- a/packages/google-cloud-storageinsights/noxfile.py +++ b/packages/google-cloud-storageinsights/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2018 Google LLC +# Copyright 2023 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-storageinsights/scripts/decrypt-secrets.sh b/packages/google-cloud-storageinsights/scripts/decrypt-secrets.sh index 21f6d2a26d90..0018b421ddf8 100755 --- a/packages/google-cloud-storageinsights/scripts/decrypt-secrets.sh +++ b/packages/google-cloud-storageinsights/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2015 Google Inc. All rights reserved. +# Copyright 2023 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License.