diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 0000000..6409f0c --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/metastore/__init__.py + google/cloud/metastore/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/v1/.flake8 b/owl-bot-staging/v1/.flake8 new file mode 100644 index 0000000..29227d4 --- /dev/null +++ b/owl-bot-staging/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/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in new file mode 100644 index 0000000..d4a653b --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/metastore *.py +recursive-include google/cloud/metastore_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 0000000..f16e3c2 --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Metastore 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 Metastore 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/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 0000000..74eaefd --- /dev/null +++ b/owl-bot-staging/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-dataproc-metastore 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-dataproc-metastore" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google 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-dataproc-metastore-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-dataproc-metastore.tex", + u"google-cloud-dataproc-metastore 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-dataproc-metastore", + u"Google Cloud Metastore 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-dataproc-metastore", + u"google-cloud-dataproc-metastore Documentation", + author, + "google-cloud-dataproc-metastore", + "GAPIC library for Google Cloud Metastore 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/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 0000000..53fd465 --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + metastore_v1/services + metastore_v1/types diff --git a/owl-bot-staging/v1/docs/metastore_v1/dataproc_metastore.rst b/owl-bot-staging/v1/docs/metastore_v1/dataproc_metastore.rst new file mode 100644 index 0000000..8be84f5 --- /dev/null +++ b/owl-bot-staging/v1/docs/metastore_v1/dataproc_metastore.rst @@ -0,0 +1,10 @@ +DataprocMetastore +----------------------------------- + +.. automodule:: google.cloud.metastore_v1.services.dataproc_metastore + :members: + :inherited-members: + +.. automodule:: google.cloud.metastore_v1.services.dataproc_metastore.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/metastore_v1/dataproc_metastore_federation.rst b/owl-bot-staging/v1/docs/metastore_v1/dataproc_metastore_federation.rst new file mode 100644 index 0000000..78c95c8 --- /dev/null +++ b/owl-bot-staging/v1/docs/metastore_v1/dataproc_metastore_federation.rst @@ -0,0 +1,10 @@ +DataprocMetastoreFederation +--------------------------------------------- + +.. automodule:: google.cloud.metastore_v1.services.dataproc_metastore_federation + :members: + :inherited-members: + +.. automodule:: google.cloud.metastore_v1.services.dataproc_metastore_federation.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/metastore_v1/services.rst b/owl-bot-staging/v1/docs/metastore_v1/services.rst new file mode 100644 index 0000000..2bb0a56 --- /dev/null +++ b/owl-bot-staging/v1/docs/metastore_v1/services.rst @@ -0,0 +1,7 @@ +Services for Google Cloud Metastore v1 API +========================================== +.. toctree:: + :maxdepth: 2 + + dataproc_metastore + dataproc_metastore_federation diff --git a/owl-bot-staging/v1/docs/metastore_v1/types.rst b/owl-bot-staging/v1/docs/metastore_v1/types.rst new file mode 100644 index 0000000..cc9df1b --- /dev/null +++ b/owl-bot-staging/v1/docs/metastore_v1/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Metastore v1 API +======================================= + +.. automodule:: google.cloud.metastore_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v1/google/cloud/metastore/__init__.py b/owl-bot-staging/v1/google/cloud/metastore/__init__.py new file mode 100644 index 0000000..b85843d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore/__init__.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.metastore import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.metastore_v1.services.dataproc_metastore.client import DataprocMetastoreClient +from google.cloud.metastore_v1.services.dataproc_metastore.async_client import DataprocMetastoreAsyncClient +from google.cloud.metastore_v1.services.dataproc_metastore_federation.client import DataprocMetastoreFederationClient +from google.cloud.metastore_v1.services.dataproc_metastore_federation.async_client import DataprocMetastoreFederationAsyncClient + +from google.cloud.metastore_v1.types.metastore import Backup +from google.cloud.metastore_v1.types.metastore import CreateBackupRequest +from google.cloud.metastore_v1.types.metastore import CreateMetadataImportRequest +from google.cloud.metastore_v1.types.metastore import CreateServiceRequest +from google.cloud.metastore_v1.types.metastore import DatabaseDumpSpec +from google.cloud.metastore_v1.types.metastore import DeleteBackupRequest +from google.cloud.metastore_v1.types.metastore import DeleteServiceRequest +from google.cloud.metastore_v1.types.metastore import EncryptionConfig +from google.cloud.metastore_v1.types.metastore import ExportMetadataRequest +from google.cloud.metastore_v1.types.metastore import GetBackupRequest +from google.cloud.metastore_v1.types.metastore import GetMetadataImportRequest +from google.cloud.metastore_v1.types.metastore import GetServiceRequest +from google.cloud.metastore_v1.types.metastore import HiveMetastoreConfig +from google.cloud.metastore_v1.types.metastore import KerberosConfig +from google.cloud.metastore_v1.types.metastore import ListBackupsRequest +from google.cloud.metastore_v1.types.metastore import ListBackupsResponse +from google.cloud.metastore_v1.types.metastore import ListMetadataImportsRequest +from google.cloud.metastore_v1.types.metastore import ListMetadataImportsResponse +from google.cloud.metastore_v1.types.metastore import ListServicesRequest +from google.cloud.metastore_v1.types.metastore import ListServicesResponse +from google.cloud.metastore_v1.types.metastore import LocationMetadata +from google.cloud.metastore_v1.types.metastore import MaintenanceWindow +from google.cloud.metastore_v1.types.metastore import MetadataExport +from google.cloud.metastore_v1.types.metastore import MetadataImport +from google.cloud.metastore_v1.types.metastore import MetadataManagementActivity +from google.cloud.metastore_v1.types.metastore import NetworkConfig +from google.cloud.metastore_v1.types.metastore import OperationMetadata +from google.cloud.metastore_v1.types.metastore import Restore +from google.cloud.metastore_v1.types.metastore import RestoreServiceRequest +from google.cloud.metastore_v1.types.metastore import Secret +from google.cloud.metastore_v1.types.metastore import Service +from google.cloud.metastore_v1.types.metastore import TelemetryConfig +from google.cloud.metastore_v1.types.metastore import UpdateMetadataImportRequest +from google.cloud.metastore_v1.types.metastore import UpdateServiceRequest +from google.cloud.metastore_v1.types.metastore_federation import BackendMetastore +from google.cloud.metastore_v1.types.metastore_federation import CreateFederationRequest +from google.cloud.metastore_v1.types.metastore_federation import DeleteFederationRequest +from google.cloud.metastore_v1.types.metastore_federation import Federation +from google.cloud.metastore_v1.types.metastore_federation import GetFederationRequest +from google.cloud.metastore_v1.types.metastore_federation import ListFederationsRequest +from google.cloud.metastore_v1.types.metastore_federation import ListFederationsResponse +from google.cloud.metastore_v1.types.metastore_federation import UpdateFederationRequest + +__all__ = ('DataprocMetastoreClient', + 'DataprocMetastoreAsyncClient', + 'DataprocMetastoreFederationClient', + 'DataprocMetastoreFederationAsyncClient', + 'Backup', + 'CreateBackupRequest', + 'CreateMetadataImportRequest', + 'CreateServiceRequest', + 'DatabaseDumpSpec', + 'DeleteBackupRequest', + 'DeleteServiceRequest', + 'EncryptionConfig', + 'ExportMetadataRequest', + 'GetBackupRequest', + 'GetMetadataImportRequest', + 'GetServiceRequest', + 'HiveMetastoreConfig', + 'KerberosConfig', + 'ListBackupsRequest', + 'ListBackupsResponse', + 'ListMetadataImportsRequest', + 'ListMetadataImportsResponse', + 'ListServicesRequest', + 'ListServicesResponse', + 'LocationMetadata', + 'MaintenanceWindow', + 'MetadataExport', + 'MetadataImport', + 'MetadataManagementActivity', + 'NetworkConfig', + 'OperationMetadata', + 'Restore', + 'RestoreServiceRequest', + 'Secret', + 'Service', + 'TelemetryConfig', + 'UpdateMetadataImportRequest', + 'UpdateServiceRequest', + 'BackendMetastore', + 'CreateFederationRequest', + 'DeleteFederationRequest', + 'Federation', + 'GetFederationRequest', + 'ListFederationsRequest', + 'ListFederationsResponse', + 'UpdateFederationRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/metastore/gapic_version.py b/owl-bot-staging/v1/google/cloud/metastore/gapic_version.py new file mode 100644 index 0000000..405b1ce --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/metastore/py.typed b/owl-bot-staging/v1/google/cloud/metastore/py.typed new file mode 100644 index 0000000..f949c43 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-dataproc-metastore package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/__init__.py b/owl-bot-staging/v1/google/cloud/metastore_v1/__init__.py new file mode 100644 index 0000000..276144d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/__init__.py @@ -0,0 +1,116 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.metastore_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.dataproc_metastore import DataprocMetastoreClient +from .services.dataproc_metastore import DataprocMetastoreAsyncClient +from .services.dataproc_metastore_federation import DataprocMetastoreFederationClient +from .services.dataproc_metastore_federation import DataprocMetastoreFederationAsyncClient + +from .types.metastore import Backup +from .types.metastore import CreateBackupRequest +from .types.metastore import CreateMetadataImportRequest +from .types.metastore import CreateServiceRequest +from .types.metastore import DatabaseDumpSpec +from .types.metastore import DeleteBackupRequest +from .types.metastore import DeleteServiceRequest +from .types.metastore import EncryptionConfig +from .types.metastore import ExportMetadataRequest +from .types.metastore import GetBackupRequest +from .types.metastore import GetMetadataImportRequest +from .types.metastore import GetServiceRequest +from .types.metastore import HiveMetastoreConfig +from .types.metastore import KerberosConfig +from .types.metastore import ListBackupsRequest +from .types.metastore import ListBackupsResponse +from .types.metastore import ListMetadataImportsRequest +from .types.metastore import ListMetadataImportsResponse +from .types.metastore import ListServicesRequest +from .types.metastore import ListServicesResponse +from .types.metastore import LocationMetadata +from .types.metastore import MaintenanceWindow +from .types.metastore import MetadataExport +from .types.metastore import MetadataImport +from .types.metastore import MetadataManagementActivity +from .types.metastore import NetworkConfig +from .types.metastore import OperationMetadata +from .types.metastore import Restore +from .types.metastore import RestoreServiceRequest +from .types.metastore import Secret +from .types.metastore import Service +from .types.metastore import TelemetryConfig +from .types.metastore import UpdateMetadataImportRequest +from .types.metastore import UpdateServiceRequest +from .types.metastore_federation import BackendMetastore +from .types.metastore_federation import CreateFederationRequest +from .types.metastore_federation import DeleteFederationRequest +from .types.metastore_federation import Federation +from .types.metastore_federation import GetFederationRequest +from .types.metastore_federation import ListFederationsRequest +from .types.metastore_federation import ListFederationsResponse +from .types.metastore_federation import UpdateFederationRequest + +__all__ = ( + 'DataprocMetastoreAsyncClient', + 'DataprocMetastoreFederationAsyncClient', +'BackendMetastore', +'Backup', +'CreateBackupRequest', +'CreateFederationRequest', +'CreateMetadataImportRequest', +'CreateServiceRequest', +'DatabaseDumpSpec', +'DataprocMetastoreClient', +'DataprocMetastoreFederationClient', +'DeleteBackupRequest', +'DeleteFederationRequest', +'DeleteServiceRequest', +'EncryptionConfig', +'ExportMetadataRequest', +'Federation', +'GetBackupRequest', +'GetFederationRequest', +'GetMetadataImportRequest', +'GetServiceRequest', +'HiveMetastoreConfig', +'KerberosConfig', +'ListBackupsRequest', +'ListBackupsResponse', +'ListFederationsRequest', +'ListFederationsResponse', +'ListMetadataImportsRequest', +'ListMetadataImportsResponse', +'ListServicesRequest', +'ListServicesResponse', +'LocationMetadata', +'MaintenanceWindow', +'MetadataExport', +'MetadataImport', +'MetadataManagementActivity', +'NetworkConfig', +'OperationMetadata', +'Restore', +'RestoreServiceRequest', +'Secret', +'Service', +'TelemetryConfig', +'UpdateFederationRequest', +'UpdateMetadataImportRequest', +'UpdateServiceRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/metastore_v1/gapic_metadata.json new file mode 100644 index 0000000..f605280 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/gapic_metadata.json @@ -0,0 +1,347 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.metastore_v1", + "protoPackage": "google.cloud.metastore.v1", + "schema": "1.0", + "services": { + "DataprocMetastore": { + "clients": { + "grpc": { + "libraryClient": "DataprocMetastoreClient", + "rpcs": { + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateMetadataImport": { + "methods": [ + "create_metadata_import" + ] + }, + "CreateService": { + "methods": [ + "create_service" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "ExportMetadata": { + "methods": [ + "export_metadata" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetMetadataImport": { + "methods": [ + "get_metadata_import" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListMetadataImports": { + "methods": [ + "list_metadata_imports" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "RestoreService": { + "methods": [ + "restore_service" + ] + }, + "UpdateMetadataImport": { + "methods": [ + "update_metadata_import" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DataprocMetastoreAsyncClient", + "rpcs": { + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateMetadataImport": { + "methods": [ + "create_metadata_import" + ] + }, + "CreateService": { + "methods": [ + "create_service" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "ExportMetadata": { + "methods": [ + "export_metadata" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetMetadataImport": { + "methods": [ + "get_metadata_import" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListMetadataImports": { + "methods": [ + "list_metadata_imports" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "RestoreService": { + "methods": [ + "restore_service" + ] + }, + "UpdateMetadataImport": { + "methods": [ + "update_metadata_import" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + }, + "rest": { + "libraryClient": "DataprocMetastoreClient", + "rpcs": { + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateMetadataImport": { + "methods": [ + "create_metadata_import" + ] + }, + "CreateService": { + "methods": [ + "create_service" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "ExportMetadata": { + "methods": [ + "export_metadata" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetMetadataImport": { + "methods": [ + "get_metadata_import" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListMetadataImports": { + "methods": [ + "list_metadata_imports" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "RestoreService": { + "methods": [ + "restore_service" + ] + }, + "UpdateMetadataImport": { + "methods": [ + "update_metadata_import" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + } + } + }, + "DataprocMetastoreFederation": { + "clients": { + "grpc": { + "libraryClient": "DataprocMetastoreFederationClient", + "rpcs": { + "CreateFederation": { + "methods": [ + "create_federation" + ] + }, + "DeleteFederation": { + "methods": [ + "delete_federation" + ] + }, + "GetFederation": { + "methods": [ + "get_federation" + ] + }, + "ListFederations": { + "methods": [ + "list_federations" + ] + }, + "UpdateFederation": { + "methods": [ + "update_federation" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DataprocMetastoreFederationAsyncClient", + "rpcs": { + "CreateFederation": { + "methods": [ + "create_federation" + ] + }, + "DeleteFederation": { + "methods": [ + "delete_federation" + ] + }, + "GetFederation": { + "methods": [ + "get_federation" + ] + }, + "ListFederations": { + "methods": [ + "list_federations" + ] + }, + "UpdateFederation": { + "methods": [ + "update_federation" + ] + } + } + }, + "rest": { + "libraryClient": "DataprocMetastoreFederationClient", + "rpcs": { + "CreateFederation": { + "methods": [ + "create_federation" + ] + }, + "DeleteFederation": { + "methods": [ + "delete_federation" + ] + }, + "GetFederation": { + "methods": [ + "get_federation" + ] + }, + "ListFederations": { + "methods": [ + "list_federations" + ] + }, + "UpdateFederation": { + "methods": [ + "update_federation" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/gapic_version.py b/owl-bot-staging/v1/google/cloud/metastore_v1/gapic_version.py new file mode 100644 index 0000000..405b1ce --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/py.typed b/owl-bot-staging/v1/google/cloud/metastore_v1/py.typed new file mode 100644 index 0000000..f949c43 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-dataproc-metastore package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/__init__.py new file mode 100644 index 0000000..e8e1c38 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/__init__.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/__init__.py new file mode 100644 index 0000000..fb93e40 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import DataprocMetastoreClient +from .async_client import DataprocMetastoreAsyncClient + +__all__ = ( + 'DataprocMetastoreClient', + 'DataprocMetastoreAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/async_client.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/async_client.py new file mode 100644 index 0000000..719d001 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/async_client.py @@ -0,0 +1,2626 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.metastore_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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1.services.dataproc_metastore import pagers +from google.cloud.metastore_v1.types import metastore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DataprocMetastoreTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DataprocMetastoreGrpcAsyncIOTransport +from .client import DataprocMetastoreClient + + +class DataprocMetastoreAsyncClient: + """Configures and manages metastore services. Metastore services are + fully managed, highly available, autoscaled, autohealing, OSS-native + deployments of technical metadata management software. Each + metastore service exposes a network endpoint through which metadata + queries are served. Metadata queries can originate from a variety of + sources, including Apache Hive, Apache Presto, and Apache Spark. + + The Dataproc Metastore API defines the following resource model: + + - The service works with a collection of Google Cloud projects, + named: ``/projects/*`` + + - Each project has a collection of available locations, named: + ``/locations/*`` (a location must refer to a Google Cloud + ``region``) + + - Each location has a collection of services, named: + ``/services/*`` + + - Dataproc Metastore services are resources with names of the form: + + ``/projects/{project_number}/locations/{location_id}/services/{service_id}``. + """ + + _client: DataprocMetastoreClient + + DEFAULT_ENDPOINT = DataprocMetastoreClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DataprocMetastoreClient.DEFAULT_MTLS_ENDPOINT + + backup_path = staticmethod(DataprocMetastoreClient.backup_path) + parse_backup_path = staticmethod(DataprocMetastoreClient.parse_backup_path) + metadata_import_path = staticmethod(DataprocMetastoreClient.metadata_import_path) + parse_metadata_import_path = staticmethod(DataprocMetastoreClient.parse_metadata_import_path) + network_path = staticmethod(DataprocMetastoreClient.network_path) + parse_network_path = staticmethod(DataprocMetastoreClient.parse_network_path) + service_path = staticmethod(DataprocMetastoreClient.service_path) + parse_service_path = staticmethod(DataprocMetastoreClient.parse_service_path) + subnetwork_path = staticmethod(DataprocMetastoreClient.subnetwork_path) + parse_subnetwork_path = staticmethod(DataprocMetastoreClient.parse_subnetwork_path) + common_billing_account_path = staticmethod(DataprocMetastoreClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DataprocMetastoreClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DataprocMetastoreClient.common_folder_path) + parse_common_folder_path = staticmethod(DataprocMetastoreClient.parse_common_folder_path) + common_organization_path = staticmethod(DataprocMetastoreClient.common_organization_path) + parse_common_organization_path = staticmethod(DataprocMetastoreClient.parse_common_organization_path) + common_project_path = staticmethod(DataprocMetastoreClient.common_project_path) + parse_common_project_path = staticmethod(DataprocMetastoreClient.parse_common_project_path) + common_location_path = staticmethod(DataprocMetastoreClient.common_location_path) + parse_common_location_path = staticmethod(DataprocMetastoreClient.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: + DataprocMetastoreAsyncClient: The constructed client. + """ + return DataprocMetastoreClient.from_service_account_info.__func__(DataprocMetastoreAsyncClient, 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: + DataprocMetastoreAsyncClient: The constructed client. + """ + return DataprocMetastoreClient.from_service_account_file.__func__(DataprocMetastoreAsyncClient, 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 DataprocMetastoreClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DataprocMetastoreTransport: + """Returns the transport used by the client instance. + + Returns: + DataprocMetastoreTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DataprocMetastoreClient).get_transport_class, type(DataprocMetastoreClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DataprocMetastoreTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dataproc metastore 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, ~.DataprocMetastoreTransport]): 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 = DataprocMetastoreClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_services(self, + request: Optional[Union[metastore.ListServicesRequest, 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.ListServicesAsyncPager: + r"""Lists services in a 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 metastore_v1 + + async def sample_list_services(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.ListServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.ListServicesRequest, dict]]): + The request object. Request message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1.DataprocMetastore.ListServices]. + parent (:class:`str`): + Required. The relative resource name of the location of + metastore services to list, in the following form: + + ``projects/{project_number}/locations/{location_id}``. + + 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.metastore_v1.services.dataproc_metastore.pagers.ListServicesAsyncPager: + Response message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1.DataprocMetastore.ListServices]. + + 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 = metastore.ListServicesRequest(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_services, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListServicesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_service(self, + request: Optional[Union[metastore.GetServiceRequest, 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]] = (), + ) -> metastore.Service: + r"""Gets the details of a single service. + + .. 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 metastore_v1 + + async def sample_get_service(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.GetServiceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_service(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.GetServiceRequest, dict]]): + The request object. Request message for + [DataprocMetastore.GetService][google.cloud.metastore.v1.DataprocMetastore.GetService]. + name (:class:`str`): + Required. The relative resource name of the metastore + service to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + 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.metastore_v1.types.Service: + A managed metastore service that + serves metadata queries. + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 = metastore.GetServiceRequest(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_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_service(self, + request: Optional[Union[metastore.CreateServiceRequest, dict]] = None, + *, + parent: Optional[str] = None, + service: Optional[metastore.Service] = None, + service_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a metastore service in a 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 metastore_v1 + + async def sample_create_service(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.CreateServiceRequest( + parent="parent_value", + service_id="service_id_value", + ) + + # Make the request + operation = client.create_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.CreateServiceRequest, dict]]): + The request object. Request message for + [DataprocMetastore.CreateService][google.cloud.metastore.v1.DataprocMetastore.CreateService]. + parent (:class:`str`): + Required. The relative resource name of the location in + which to create a metastore service, in the following + form: + + ``projects/{project_number}/locations/{location_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service (:class:`google.cloud.metastore_v1.types.Service`): + Required. The Metastore service to create. The ``name`` + field is ignored. The ID of the created metastore + service must be provided in the request's ``service_id`` + field. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_id (:class:`str`): + Required. The ID of the metastore + service, which is used as the final + component of the metastore service's + name. + This value must be between 2 and 63 + characters long inclusive, begin with a + letter, end with a letter or number, and + consist of alpha-numeric ASCII + characters or hyphens. + + This corresponds to the ``service_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1.types.Service` A + managed metastore service that serves metadata queries. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, service, service_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = metastore.CreateServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if service is not None: + request.service = service + if service_id is not None: + request.service_id = service_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_service, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.Service, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_service(self, + request: Optional[Union[metastore.UpdateServiceRequest, dict]] = None, + *, + service: Optional[metastore.Service] = 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single service. + + .. 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 metastore_v1 + + async def sample_update_service(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.UpdateServiceRequest( + ) + + # Make the request + operation = client.update_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.UpdateServiceRequest, dict]]): + The request object. Request message for + [DataprocMetastore.UpdateService][google.cloud.metastore.v1.DataprocMetastore.UpdateService]. + service (:class:`google.cloud.metastore_v1.types.Service`): + Required. The metastore service to update. The server + only merges fields in the service if they are specified + in ``update_mask``. + + The metastore service's ``name`` field is used to + identify the metastore service to be updated. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. A field mask used to specify the fields to be + overwritten in the metastore service resource by the + update. Fields specified in the ``update_mask`` are + relative to the resource (not to the full request). A + field is overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1.types.Service` A + managed metastore service that serves metadata queries. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, 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 = metastore.UpdateServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if service is not None: + request.service = service + 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_service, + 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(( + ("service.name", request.service.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.Service, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_service(self, + request: Optional[Union[metastore.DeleteServiceRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single service. + + .. 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 metastore_v1 + + async def sample_delete_service(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.DeleteServiceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.DeleteServiceRequest, dict]]): + The request object. Request message for + [DataprocMetastore.DeleteService][google.cloud.metastore.v1.DataprocMetastore.DeleteService]. + name (:class:`str`): + Required. The relative resource name of the metastore + service to delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 = metastore.DeleteServiceRequest(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_service, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_metadata_imports(self, + request: Optional[Union[metastore.ListMetadataImportsRequest, 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.ListMetadataImportsAsyncPager: + r"""Lists imports in a service. + + .. 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 metastore_v1 + + async def sample_list_metadata_imports(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.ListMetadataImportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_metadata_imports(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.ListMetadataImportsRequest, dict]]): + The request object. Request message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1.DataprocMetastore.ListMetadataImports]. + parent (:class:`str`): + Required. The relative resource name of the service + whose metadata imports to list, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports``. + + 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.metastore_v1.services.dataproc_metastore.pagers.ListMetadataImportsAsyncPager: + Response message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1.DataprocMetastore.ListMetadataImports]. + + 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 = metastore.ListMetadataImportsRequest(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_metadata_imports, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMetadataImportsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_metadata_import(self, + request: Optional[Union[metastore.GetMetadataImportRequest, 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]] = (), + ) -> metastore.MetadataImport: + r"""Gets details of a single import. + + .. 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 metastore_v1 + + async def sample_get_metadata_import(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.GetMetadataImportRequest( + name="name_value", + ) + + # Make the request + response = await client.get_metadata_import(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.GetMetadataImportRequest, dict]]): + The request object. Request message for + [DataprocMetastore.GetMetadataImport][google.cloud.metastore.v1.DataprocMetastore.GetMetadataImport]. + name (:class:`str`): + Required. The relative resource name of the metadata + import to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports/{import_id}``. + + 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.metastore_v1.types.MetadataImport: + A metastore resource that imports + 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 = metastore.GetMetadataImportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_metadata_import, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_metadata_import(self, + request: Optional[Union[metastore.CreateMetadataImportRequest, dict]] = None, + *, + parent: Optional[str] = None, + metadata_import: Optional[metastore.MetadataImport] = None, + metadata_import_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new MetadataImport 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 metastore_v1 + + async def sample_create_metadata_import(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.CreateMetadataImportRequest( + parent="parent_value", + metadata_import_id="metadata_import_id_value", + ) + + # Make the request + operation = client.create_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.CreateMetadataImportRequest, dict]]): + The request object. Request message for + [DataprocMetastore.CreateMetadataImport][google.cloud.metastore.v1.DataprocMetastore.CreateMetadataImport]. + parent (:class:`str`): + Required. The relative resource name of the service in + which to create a metastore import, in the following + form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + metadata_import (:class:`google.cloud.metastore_v1.types.MetadataImport`): + Required. The metadata import to create. The ``name`` + field is ignored. The ID of the created metadata import + must be provided in the request's ``metadata_import_id`` + field. + + This corresponds to the ``metadata_import`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + metadata_import_id (:class:`str`): + Required. The ID of the metadata + import, which is used as the final + component of the metadata import's name. + This value must be between 1 and 64 + characters long, begin with a letter, + end with a letter or number, and consist + of alpha-numeric ASCII characters or + hyphens. + + This corresponds to the ``metadata_import_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1.types.MetadataImport` + A metastore resource that imports 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([parent, metadata_import, metadata_import_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = metastore.CreateMetadataImportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if metadata_import is not None: + request.metadata_import = metadata_import + if metadata_import_id is not None: + request.metadata_import_id = metadata_import_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_metadata_import, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.MetadataImport, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_metadata_import(self, + request: Optional[Union[metastore.UpdateMetadataImportRequest, dict]] = None, + *, + metadata_import: Optional[metastore.MetadataImport] = 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a single import. + Only the description field of MetadataImport is + supported to be updated. + + .. 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 metastore_v1 + + async def sample_update_metadata_import(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.UpdateMetadataImportRequest( + ) + + # Make the request + operation = client.update_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.UpdateMetadataImportRequest, dict]]): + The request object. Request message for + [DataprocMetastore.UpdateMetadataImport][google.cloud.metastore.v1.DataprocMetastore.UpdateMetadataImport]. + metadata_import (:class:`google.cloud.metastore_v1.types.MetadataImport`): + Required. The metadata import to update. The server only + merges fields in the import if they are specified in + ``update_mask``. + + The metadata import's ``name`` field is used to identify + the metastore import to be updated. + + This corresponds to the ``metadata_import`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. A field mask used to specify the fields to be + overwritten in the metadata import resource by the + update. Fields specified in the ``update_mask`` are + relative to the resource (not to the full request). A + field is overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1.types.MetadataImport` + A metastore resource that imports 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([metadata_import, 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 = metastore.UpdateMetadataImportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if metadata_import is not None: + request.metadata_import = metadata_import + 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_metadata_import, + 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(( + ("metadata_import.name", request.metadata_import.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.MetadataImport, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def export_metadata(self, + request: Optional[Union[metastore.ExportMetadataRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports metadata from a service. + + .. 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 metastore_v1 + + async def sample_export_metadata(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.ExportMetadataRequest( + destination_gcs_folder="destination_gcs_folder_value", + service="service_value", + ) + + # Make the request + operation = client.export_metadata(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.ExportMetadataRequest, dict]]): + The request object. Request message for + [DataprocMetastore.ExportMetadata][google.cloud.metastore.v1.DataprocMetastore.ExportMetadata]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1.types.MetadataExport` + The details of a metadata export operation. + + """ + # Create or coerce a protobuf request object. + request = metastore.ExportMetadataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_metadata, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service", request.service), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.MetadataExport, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def restore_service(self, + request: Optional[Union[metastore.RestoreServiceRequest, dict]] = None, + *, + service: Optional[str] = None, + backup: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Restores a service from a backup. + + .. 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 metastore_v1 + + async def sample_restore_service(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.RestoreServiceRequest( + service="service_value", + backup="backup_value", + ) + + # Make the request + operation = client.restore_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.RestoreServiceRequest, dict]]): + The request object. Request message for [DataprocMetastore.Restore][]. + service (:class:`str`): + Required. The relative resource name of the metastore + service to run restore, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup (:class:`str`): + Required. The relative resource name of the metastore + service backup to restore from, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1.types.Restore` The + details of a metadata restore operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, backup]) + if request is 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 = metastore.RestoreServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if service is not None: + request.service = service + if backup is not None: + request.backup = backup + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.restore_service, + 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(( + ("service", request.service), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.Restore, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_backups(self, + request: Optional[Union[metastore.ListBackupsRequest, 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.ListBackupsAsyncPager: + r"""Lists backups in a service. + + .. 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 metastore_v1 + + async def sample_list_backups(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.ListBackupsRequest, dict]]): + The request object. Request message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1.DataprocMetastore.ListBackups]. + parent (:class:`str`): + Required. The relative resource name of the service + whose backups to list, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups``. + + 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.metastore_v1.services.dataproc_metastore.pagers.ListBackupsAsyncPager: + Response message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1.DataprocMetastore.ListBackups]. + + 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 = metastore.ListBackupsRequest(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_backups, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListBackupsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_backup(self, + request: Optional[Union[metastore.GetBackupRequest, 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]] = (), + ) -> metastore.Backup: + r"""Gets details of a single backup. + + .. 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 metastore_v1 + + async def sample_get_backup(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.GetBackupRequest, dict]]): + The request object. Request message for + [DataprocMetastore.GetBackup][google.cloud.metastore.v1.DataprocMetastore.GetBackup]. + name (:class:`str`): + Required. The relative resource name of the backup to + retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + + 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.metastore_v1.types.Backup: + The details of a backup resource. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = metastore.GetBackupRequest(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_backup, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_backup(self, + request: Optional[Union[metastore.CreateBackupRequest, dict]] = None, + *, + parent: Optional[str] = None, + backup: Optional[metastore.Backup] = None, + backup_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new backup 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 metastore_v1 + + async def sample_create_backup(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + ) + + # Make the request + operation = client.create_backup(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.CreateBackupRequest, dict]]): + The request object. Request message for + [DataprocMetastore.CreateBackup][google.cloud.metastore.v1.DataprocMetastore.CreateBackup]. + parent (:class:`str`): + Required. The relative resource name of the service in + which to create a backup of the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup (:class:`google.cloud.metastore_v1.types.Backup`): + Required. The backup to create. The ``name`` field is + ignored. The ID of the created backup must be provided + in the request's ``backup_id`` field. + + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_id (:class:`str`): + Required. The ID of the backup, which + is used as the final component of the + backup's name. + This value must be between 1 and 64 + characters long, begin with a letter, + end with a letter or number, and consist + of alpha-numeric ASCII characters or + hyphens. + + This corresponds to the ``backup_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1.types.Backup` The + details of a backup resource. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, backup, backup_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = metastore.CreateBackupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if backup is not None: + request.backup = backup + if backup_id is not None: + request.backup_id = backup_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_backup, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.Backup, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_backup(self, + request: Optional[Union[metastore.DeleteBackupRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single backup. + + .. 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 metastore_v1 + + async def sample_delete_backup(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.DeleteBackupRequest, dict]]): + The request object. Request message for + [DataprocMetastore.DeleteBackup][google.cloud.metastore.v1.DataprocMetastore.DeleteBackup]. + name (:class:`str`): + Required. The relative resource name of the backup to + delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 = metastore.DeleteBackupRequest(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_backup, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=metastore.OperationMetadata, + ) + + # 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.set_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.GetIamPolicyRequest(**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_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.test_iam_permissions, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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): + 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__ = ( + "DataprocMetastoreAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/client.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/client.py new file mode 100644 index 0000000..5033986 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/client.py @@ -0,0 +1,2862 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.metastore_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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1.services.dataproc_metastore import pagers +from google.cloud.metastore_v1.types import metastore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DataprocMetastoreTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DataprocMetastoreGrpcTransport +from .transports.grpc_asyncio import DataprocMetastoreGrpcAsyncIOTransport +from .transports.rest import DataprocMetastoreRestTransport + + +class DataprocMetastoreClientMeta(type): + """Metaclass for the DataprocMetastore 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[DataprocMetastoreTransport]] + _transport_registry["grpc"] = DataprocMetastoreGrpcTransport + _transport_registry["grpc_asyncio"] = DataprocMetastoreGrpcAsyncIOTransport + _transport_registry["rest"] = DataprocMetastoreRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[DataprocMetastoreTransport]: + """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 DataprocMetastoreClient(metaclass=DataprocMetastoreClientMeta): + """Configures and manages metastore services. Metastore services are + fully managed, highly available, autoscaled, autohealing, OSS-native + deployments of technical metadata management software. Each + metastore service exposes a network endpoint through which metadata + queries are served. Metadata queries can originate from a variety of + sources, including Apache Hive, Apache Presto, and Apache Spark. + + The Dataproc Metastore API defines the following resource model: + + - The service works with a collection of Google Cloud projects, + named: ``/projects/*`` + + - Each project has a collection of available locations, named: + ``/locations/*`` (a location must refer to a Google Cloud + ``region``) + + - Each location has a collection of services, named: + ``/services/*`` + + - Dataproc Metastore services are resources with names of the form: + + ``/projects/{project_number}/locations/{location_id}/services/{service_id}``. + """ + + @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 = "metastore.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: + DataprocMetastoreClient: 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: + DataprocMetastoreClient: 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) -> DataprocMetastoreTransport: + """Returns the transport used by the client instance. + + Returns: + DataprocMetastoreTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def backup_path(project: str,location: str,service: str,backup: str,) -> str: + """Returns a fully-qualified backup string.""" + return "projects/{project}/locations/{location}/services/{service}/backups/{backup}".format(project=project, location=location, service=service, backup=backup, ) + + @staticmethod + def parse_backup_path(path: str) -> Dict[str,str]: + """Parses a backup path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/services/(?P.+?)/backups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def metadata_import_path(project: str,location: str,service: str,metadata_import: str,) -> str: + """Returns a fully-qualified metadata_import string.""" + return "projects/{project}/locations/{location}/services/{service}/metadataImports/{metadata_import}".format(project=project, location=location, service=service, metadata_import=metadata_import, ) + + @staticmethod + def parse_metadata_import_path(path: str) -> Dict[str,str]: + """Parses a metadata_import path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/services/(?P.+?)/metadataImports/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def network_path(project: str,network: str,) -> str: + """Returns a fully-qualified network string.""" + return "projects/{project}/global/networks/{network}".format(project=project, network=network, ) + + @staticmethod + def parse_network_path(path: str) -> Dict[str,str]: + """Parses a network path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/global/networks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_path(project: str,location: str,service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/services/{service}".format(project=project, location=location, service=service, ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str,str]: + """Parses a service path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/services/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def subnetwork_path(project: str,region: str,subnetwork: str,) -> str: + """Returns a fully-qualified subnetwork string.""" + return "projects/{project}/regions/{region}/subnetworks/{subnetwork}".format(project=project, region=region, subnetwork=subnetwork, ) + + @staticmethod + def parse_subnetwork_path(path: str) -> Dict[str,str]: + """Parses a subnetwork path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/regions/(?P.+?)/subnetworks/(?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, DataprocMetastoreTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dataproc metastore 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, DataprocMetastoreTransport]): 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, DataprocMetastoreTransport): + # transport is a DataprocMetastoreTransport 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_services(self, + request: Optional[Union[metastore.ListServicesRequest, 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.ListServicesPager: + r"""Lists services in a 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 metastore_v1 + + def sample_list_services(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.ListServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.ListServicesRequest, dict]): + The request object. Request message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1.DataprocMetastore.ListServices]. + parent (str): + Required. The relative resource name of the location of + metastore services to list, in the following form: + + ``projects/{project_number}/locations/{location_id}``. + + 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.metastore_v1.services.dataproc_metastore.pagers.ListServicesPager: + Response message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1.DataprocMetastore.ListServices]. + + 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 metastore.ListServicesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.ListServicesRequest): + request = metastore.ListServicesRequest(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_services] + + # Certain 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.ListServicesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_service(self, + request: Optional[Union[metastore.GetServiceRequest, 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]] = (), + ) -> metastore.Service: + r"""Gets the details of a single service. + + .. 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 metastore_v1 + + def sample_get_service(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.GetServiceRequest( + name="name_value", + ) + + # Make the request + response = client.get_service(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.GetServiceRequest, dict]): + The request object. Request message for + [DataprocMetastore.GetService][google.cloud.metastore.v1.DataprocMetastore.GetService]. + name (str): + Required. The relative resource name of the metastore + service to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + 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.metastore_v1.types.Service: + A managed metastore service that + serves metadata queries. + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 metastore.GetServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.GetServiceRequest): + request = metastore.GetServiceRequest(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_service] + + # Certain 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_service(self, + request: Optional[Union[metastore.CreateServiceRequest, dict]] = None, + *, + parent: Optional[str] = None, + service: Optional[metastore.Service] = None, + service_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a metastore service in a 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 metastore_v1 + + def sample_create_service(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.CreateServiceRequest( + parent="parent_value", + service_id="service_id_value", + ) + + # Make the request + operation = client.create_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.CreateServiceRequest, dict]): + The request object. Request message for + [DataprocMetastore.CreateService][google.cloud.metastore.v1.DataprocMetastore.CreateService]. + parent (str): + Required. The relative resource name of the location in + which to create a metastore service, in the following + form: + + ``projects/{project_number}/locations/{location_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service (google.cloud.metastore_v1.types.Service): + Required. The Metastore service to create. The ``name`` + field is ignored. The ID of the created metastore + service must be provided in the request's ``service_id`` + field. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_id (str): + Required. The ID of the metastore + service, which is used as the final + component of the metastore service's + name. + This value must be between 2 and 63 + characters long inclusive, begin with a + letter, end with a letter or number, and + consist of alpha-numeric ASCII + characters or hyphens. + + This corresponds to the ``service_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1.types.Service` A + managed metastore service that serves metadata queries. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, service, service_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a metastore.CreateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.CreateServiceRequest): + request = metastore.CreateServiceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if service is not None: + request.service = service + if service_id is not None: + request.service_id = service_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.Service, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_service(self, + request: Optional[Union[metastore.UpdateServiceRequest, dict]] = None, + *, + service: Optional[metastore.Service] = 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]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single service. + + .. 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 metastore_v1 + + def sample_update_service(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.UpdateServiceRequest( + ) + + # Make the request + operation = client.update_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.UpdateServiceRequest, dict]): + The request object. Request message for + [DataprocMetastore.UpdateService][google.cloud.metastore.v1.DataprocMetastore.UpdateService]. + service (google.cloud.metastore_v1.types.Service): + Required. The metastore service to update. The server + only merges fields in the service if they are specified + in ``update_mask``. + + The metastore service's ``name`` field is used to + identify the metastore service to be updated. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask used to specify the fields to be + overwritten in the metastore service resource by the + update. Fields specified in the ``update_mask`` are + relative to the resource (not to the full request). A + field is overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1.types.Service` A + managed metastore service that serves metadata queries. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, 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 metastore.UpdateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.UpdateServiceRequest): + request = metastore.UpdateServiceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if service is not None: + request.service = service + 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_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service.name", request.service.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.Service, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_service(self, + request: Optional[Union[metastore.DeleteServiceRequest, 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]] = (), + ) -> operation.Operation: + r"""Deletes a single service. + + .. 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 metastore_v1 + + def sample_delete_service(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.DeleteServiceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.DeleteServiceRequest, dict]): + The request object. Request message for + [DataprocMetastore.DeleteService][google.cloud.metastore.v1.DataprocMetastore.DeleteService]. + name (str): + Required. The relative resource name of the metastore + service to delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 metastore.DeleteServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.DeleteServiceRequest): + request = metastore.DeleteServiceRequest(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_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_metadata_imports(self, + request: Optional[Union[metastore.ListMetadataImportsRequest, 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.ListMetadataImportsPager: + r"""Lists imports in a service. + + .. 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 metastore_v1 + + def sample_list_metadata_imports(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.ListMetadataImportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_metadata_imports(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.ListMetadataImportsRequest, dict]): + The request object. Request message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1.DataprocMetastore.ListMetadataImports]. + parent (str): + Required. The relative resource name of the service + whose metadata imports to list, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports``. + + 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.metastore_v1.services.dataproc_metastore.pagers.ListMetadataImportsPager: + Response message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1.DataprocMetastore.ListMetadataImports]. + + 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 metastore.ListMetadataImportsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.ListMetadataImportsRequest): + request = metastore.ListMetadataImportsRequest(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_metadata_imports] + + # Certain 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.ListMetadataImportsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_metadata_import(self, + request: Optional[Union[metastore.GetMetadataImportRequest, 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]] = (), + ) -> metastore.MetadataImport: + r"""Gets details of a single import. + + .. 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 metastore_v1 + + def sample_get_metadata_import(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.GetMetadataImportRequest( + name="name_value", + ) + + # Make the request + response = client.get_metadata_import(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.GetMetadataImportRequest, dict]): + The request object. Request message for + [DataprocMetastore.GetMetadataImport][google.cloud.metastore.v1.DataprocMetastore.GetMetadataImport]. + name (str): + Required. The relative resource name of the metadata + import to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports/{import_id}``. + + 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.metastore_v1.types.MetadataImport: + A metastore resource that imports + 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 metastore.GetMetadataImportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.GetMetadataImportRequest): + request = metastore.GetMetadataImportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_metadata_import] + + # Certain 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_metadata_import(self, + request: Optional[Union[metastore.CreateMetadataImportRequest, dict]] = None, + *, + parent: Optional[str] = None, + metadata_import: Optional[metastore.MetadataImport] = None, + metadata_import_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new MetadataImport 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 metastore_v1 + + def sample_create_metadata_import(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.CreateMetadataImportRequest( + parent="parent_value", + metadata_import_id="metadata_import_id_value", + ) + + # Make the request + operation = client.create_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.CreateMetadataImportRequest, dict]): + The request object. Request message for + [DataprocMetastore.CreateMetadataImport][google.cloud.metastore.v1.DataprocMetastore.CreateMetadataImport]. + parent (str): + Required. The relative resource name of the service in + which to create a metastore import, in the following + form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + metadata_import (google.cloud.metastore_v1.types.MetadataImport): + Required. The metadata import to create. The ``name`` + field is ignored. The ID of the created metadata import + must be provided in the request's ``metadata_import_id`` + field. + + This corresponds to the ``metadata_import`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + metadata_import_id (str): + Required. The ID of the metadata + import, which is used as the final + component of the metadata import's name. + This value must be between 1 and 64 + characters long, begin with a letter, + end with a letter or number, and consist + of alpha-numeric ASCII characters or + hyphens. + + This corresponds to the ``metadata_import_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1.types.MetadataImport` + A metastore resource that imports 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([parent, metadata_import, metadata_import_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a metastore.CreateMetadataImportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.CreateMetadataImportRequest): + request = metastore.CreateMetadataImportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if metadata_import is not None: + request.metadata_import = metadata_import + if metadata_import_id is not None: + request.metadata_import_id = metadata_import_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_metadata_import] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.MetadataImport, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_metadata_import(self, + request: Optional[Union[metastore.UpdateMetadataImportRequest, dict]] = None, + *, + metadata_import: Optional[metastore.MetadataImport] = 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]] = (), + ) -> operation.Operation: + r"""Updates a single import. + Only the description field of MetadataImport is + supported to be updated. + + .. 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 metastore_v1 + + def sample_update_metadata_import(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.UpdateMetadataImportRequest( + ) + + # Make the request + operation = client.update_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.UpdateMetadataImportRequest, dict]): + The request object. Request message for + [DataprocMetastore.UpdateMetadataImport][google.cloud.metastore.v1.DataprocMetastore.UpdateMetadataImport]. + metadata_import (google.cloud.metastore_v1.types.MetadataImport): + Required. The metadata import to update. The server only + merges fields in the import if they are specified in + ``update_mask``. + + The metadata import's ``name`` field is used to identify + the metastore import to be updated. + + This corresponds to the ``metadata_import`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask used to specify the fields to be + overwritten in the metadata import resource by the + update. Fields specified in the ``update_mask`` are + relative to the resource (not to the full request). A + field is overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1.types.MetadataImport` + A metastore resource that imports 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([metadata_import, 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 metastore.UpdateMetadataImportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.UpdateMetadataImportRequest): + request = metastore.UpdateMetadataImportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if metadata_import is not None: + request.metadata_import = metadata_import + 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_metadata_import] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("metadata_import.name", request.metadata_import.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.MetadataImport, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def export_metadata(self, + request: Optional[Union[metastore.ExportMetadataRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports metadata from a service. + + .. 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 metastore_v1 + + def sample_export_metadata(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.ExportMetadataRequest( + destination_gcs_folder="destination_gcs_folder_value", + service="service_value", + ) + + # Make the request + operation = client.export_metadata(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.ExportMetadataRequest, dict]): + The request object. Request message for + [DataprocMetastore.ExportMetadata][google.cloud.metastore.v1.DataprocMetastore.ExportMetadata]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1.types.MetadataExport` + The details of a metadata export operation. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a metastore.ExportMetadataRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.ExportMetadataRequest): + request = metastore.ExportMetadataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_metadata] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service", request.service), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.MetadataExport, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def restore_service(self, + request: Optional[Union[metastore.RestoreServiceRequest, dict]] = None, + *, + service: Optional[str] = None, + backup: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Restores a service from a backup. + + .. 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 metastore_v1 + + def sample_restore_service(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.RestoreServiceRequest( + service="service_value", + backup="backup_value", + ) + + # Make the request + operation = client.restore_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.RestoreServiceRequest, dict]): + The request object. Request message for [DataprocMetastore.Restore][]. + service (str): + Required. The relative resource name of the metastore + service to run restore, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup (str): + Required. The relative resource name of the metastore + service backup to restore from, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1.types.Restore` The + details of a metadata restore operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, backup]) + if request is 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 metastore.RestoreServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.RestoreServiceRequest): + request = metastore.RestoreServiceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if service is not None: + request.service = service + if backup is not None: + request.backup = backup + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.restore_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service", request.service), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.Restore, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_backups(self, + request: Optional[Union[metastore.ListBackupsRequest, 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.ListBackupsPager: + r"""Lists backups in a service. + + .. 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 metastore_v1 + + def sample_list_backups(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.ListBackupsRequest, dict]): + The request object. Request message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1.DataprocMetastore.ListBackups]. + parent (str): + Required. The relative resource name of the service + whose backups to list, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups``. + + 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.metastore_v1.services.dataproc_metastore.pagers.ListBackupsPager: + Response message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1.DataprocMetastore.ListBackups]. + + 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 metastore.ListBackupsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.ListBackupsRequest): + request = metastore.ListBackupsRequest(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_backups] + + # Certain 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.ListBackupsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_backup(self, + request: Optional[Union[metastore.GetBackupRequest, 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]] = (), + ) -> metastore.Backup: + r"""Gets details of a single backup. + + .. 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 metastore_v1 + + def sample_get_backup(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.GetBackupRequest, dict]): + The request object. Request message for + [DataprocMetastore.GetBackup][google.cloud.metastore.v1.DataprocMetastore.GetBackup]. + name (str): + Required. The relative resource name of the backup to + retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + + 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.metastore_v1.types.Backup: + The details of a backup resource. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a metastore.GetBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.GetBackupRequest): + request = metastore.GetBackupRequest(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_backup] + + # Certain 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_backup(self, + request: Optional[Union[metastore.CreateBackupRequest, dict]] = None, + *, + parent: Optional[str] = None, + backup: Optional[metastore.Backup] = None, + backup_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new backup 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 metastore_v1 + + def sample_create_backup(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + ) + + # Make the request + operation = client.create_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.CreateBackupRequest, dict]): + The request object. Request message for + [DataprocMetastore.CreateBackup][google.cloud.metastore.v1.DataprocMetastore.CreateBackup]. + parent (str): + Required. The relative resource name of the service in + which to create a backup of the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup (google.cloud.metastore_v1.types.Backup): + Required. The backup to create. The ``name`` field is + ignored. The ID of the created backup must be provided + in the request's ``backup_id`` field. + + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_id (str): + Required. The ID of the backup, which + is used as the final component of the + backup's name. + This value must be between 1 and 64 + characters long, begin with a letter, + end with a letter or number, and consist + of alpha-numeric ASCII characters or + hyphens. + + This corresponds to the ``backup_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1.types.Backup` The + details of a backup resource. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, backup, backup_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a metastore.CreateBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.CreateBackupRequest): + request = metastore.CreateBackupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if backup is not None: + request.backup = backup + if backup_id is not None: + request.backup_id = backup_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_backup] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.Backup, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_backup(self, + request: Optional[Union[metastore.DeleteBackupRequest, 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]] = (), + ) -> operation.Operation: + r"""Deletes a single backup. + + .. 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 metastore_v1 + + def sample_delete_backup(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.DeleteBackupRequest, dict]): + The request object. Request message for + [DataprocMetastore.DeleteBackup][google.cloud.metastore.v1.DataprocMetastore.DeleteBackup]. + name (str): + Required. The relative resource name of the backup to + delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 metastore.DeleteBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.DeleteBackupRequest): + request = metastore.DeleteBackupRequest(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_backup] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "DataprocMetastoreClient": + 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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__ = ( + "DataprocMetastoreClient", +) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/pagers.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/pagers.py new file mode 100644 index 0000000..464986f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/pagers.py @@ -0,0 +1,381 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.metastore_v1.types import metastore + + +class ListServicesPager: + """A pager for iterating through ``list_services`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1.types.ListServicesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``services`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServices`` requests and continue to iterate + through the ``services`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1.types.ListServicesResponse` + 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[..., metastore.ListServicesResponse], + request: metastore.ListServicesRequest, + response: metastore.ListServicesResponse, + *, + 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.metastore_v1.types.ListServicesRequest): + The initial request object. + response (google.cloud.metastore_v1.types.ListServicesResponse): + 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 = metastore.ListServicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[metastore.ListServicesResponse]: + 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[metastore.Service]: + for page in self.pages: + yield from page.services + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServicesAsyncPager: + """A pager for iterating through ``list_services`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1.types.ListServicesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``services`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServices`` requests and continue to iterate + through the ``services`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1.types.ListServicesResponse` + 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[metastore.ListServicesResponse]], + request: metastore.ListServicesRequest, + response: metastore.ListServicesResponse, + *, + 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.metastore_v1.types.ListServicesRequest): + The initial request object. + response (google.cloud.metastore_v1.types.ListServicesResponse): + 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 = metastore.ListServicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[metastore.ListServicesResponse]: + 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[metastore.Service]: + async def async_generator(): + async for page in self.pages: + for response in page.services: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMetadataImportsPager: + """A pager for iterating through ``list_metadata_imports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1.types.ListMetadataImportsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``metadata_imports`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMetadataImports`` requests and continue to iterate + through the ``metadata_imports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1.types.ListMetadataImportsResponse` + 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[..., metastore.ListMetadataImportsResponse], + request: metastore.ListMetadataImportsRequest, + response: metastore.ListMetadataImportsResponse, + *, + 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.metastore_v1.types.ListMetadataImportsRequest): + The initial request object. + response (google.cloud.metastore_v1.types.ListMetadataImportsResponse): + 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 = metastore.ListMetadataImportsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[metastore.ListMetadataImportsResponse]: + 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[metastore.MetadataImport]: + for page in self.pages: + yield from page.metadata_imports + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMetadataImportsAsyncPager: + """A pager for iterating through ``list_metadata_imports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1.types.ListMetadataImportsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``metadata_imports`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMetadataImports`` requests and continue to iterate + through the ``metadata_imports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1.types.ListMetadataImportsResponse` + 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[metastore.ListMetadataImportsResponse]], + request: metastore.ListMetadataImportsRequest, + response: metastore.ListMetadataImportsResponse, + *, + 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.metastore_v1.types.ListMetadataImportsRequest): + The initial request object. + response (google.cloud.metastore_v1.types.ListMetadataImportsResponse): + 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 = metastore.ListMetadataImportsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[metastore.ListMetadataImportsResponse]: + 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[metastore.MetadataImport]: + async def async_generator(): + async for page in self.pages: + for response in page.metadata_imports: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBackupsPager: + """A pager for iterating through ``list_backups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1.types.ListBackupsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``backups`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBackups`` requests and continue to iterate + through the ``backups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1.types.ListBackupsResponse` + 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[..., metastore.ListBackupsResponse], + request: metastore.ListBackupsRequest, + response: metastore.ListBackupsResponse, + *, + 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.metastore_v1.types.ListBackupsRequest): + The initial request object. + response (google.cloud.metastore_v1.types.ListBackupsResponse): + 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 = metastore.ListBackupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[metastore.ListBackupsResponse]: + 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[metastore.Backup]: + for page in self.pages: + yield from page.backups + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBackupsAsyncPager: + """A pager for iterating through ``list_backups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1.types.ListBackupsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``backups`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBackups`` requests and continue to iterate + through the ``backups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1.types.ListBackupsResponse` + 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[metastore.ListBackupsResponse]], + request: metastore.ListBackupsRequest, + response: metastore.ListBackupsResponse, + *, + 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.metastore_v1.types.ListBackupsRequest): + The initial request object. + response (google.cloud.metastore_v1.types.ListBackupsResponse): + 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 = metastore.ListBackupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[metastore.ListBackupsResponse]: + 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[metastore.Backup]: + async def async_generator(): + async for page in self.pages: + for response in page.backups: + 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/v1/google/cloud/metastore_v1/services/dataproc_metastore/transports/__init__.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/transports/__init__.py new file mode 100644 index 0000000..38e3513 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import DataprocMetastoreTransport +from .grpc import DataprocMetastoreGrpcTransport +from .grpc_asyncio import DataprocMetastoreGrpcAsyncIOTransport +from .rest import DataprocMetastoreRestTransport +from .rest import DataprocMetastoreRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DataprocMetastoreTransport]] +_transport_registry['grpc'] = DataprocMetastoreGrpcTransport +_transport_registry['grpc_asyncio'] = DataprocMetastoreGrpcAsyncIOTransport +_transport_registry['rest'] = DataprocMetastoreRestTransport + +__all__ = ( + 'DataprocMetastoreTransport', + 'DataprocMetastoreGrpcTransport', + 'DataprocMetastoreGrpcAsyncIOTransport', + 'DataprocMetastoreRestTransport', + 'DataprocMetastoreRestInterceptor', +) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/transports/base.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/transports/base.py new file mode 100644 index 0000000..3a16adf --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/transports/base.py @@ -0,0 +1,428 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.metastore_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.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1.types import metastore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class DataprocMetastoreTransport(abc.ABC): + """Abstract transport class for DataprocMetastore.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'metastore.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_services: gapic_v1.method.wrap_method( + self.list_services, + default_timeout=None, + client_info=client_info, + ), + self.get_service: gapic_v1.method.wrap_method( + self.get_service, + default_timeout=None, + client_info=client_info, + ), + self.create_service: gapic_v1.method.wrap_method( + self.create_service, + default_timeout=60.0, + client_info=client_info, + ), + self.update_service: gapic_v1.method.wrap_method( + self.update_service, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_service: gapic_v1.method.wrap_method( + self.delete_service, + default_timeout=60.0, + client_info=client_info, + ), + self.list_metadata_imports: gapic_v1.method.wrap_method( + self.list_metadata_imports, + default_timeout=None, + client_info=client_info, + ), + self.get_metadata_import: gapic_v1.method.wrap_method( + self.get_metadata_import, + default_timeout=None, + client_info=client_info, + ), + self.create_metadata_import: gapic_v1.method.wrap_method( + self.create_metadata_import, + default_timeout=60.0, + client_info=client_info, + ), + self.update_metadata_import: gapic_v1.method.wrap_method( + self.update_metadata_import, + default_timeout=60.0, + client_info=client_info, + ), + self.export_metadata: gapic_v1.method.wrap_method( + self.export_metadata, + default_timeout=60.0, + client_info=client_info, + ), + self.restore_service: gapic_v1.method.wrap_method( + self.restore_service, + default_timeout=60.0, + client_info=client_info, + ), + self.list_backups: gapic_v1.method.wrap_method( + self.list_backups, + default_timeout=None, + client_info=client_info, + ), + self.get_backup: gapic_v1.method.wrap_method( + self.get_backup, + default_timeout=None, + client_info=client_info, + ), + self.create_backup: gapic_v1.method.wrap_method( + self.create_backup, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_backup: gapic_v1.method.wrap_method( + self.delete_backup, + 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 operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_services(self) -> Callable[ + [metastore.ListServicesRequest], + Union[ + metastore.ListServicesResponse, + Awaitable[metastore.ListServicesResponse] + ]]: + raise NotImplementedError() + + @property + def get_service(self) -> Callable[ + [metastore.GetServiceRequest], + Union[ + metastore.Service, + Awaitable[metastore.Service] + ]]: + raise NotImplementedError() + + @property + def create_service(self) -> Callable[ + [metastore.CreateServiceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_service(self) -> Callable[ + [metastore.UpdateServiceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_service(self) -> Callable[ + [metastore.DeleteServiceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_metadata_imports(self) -> Callable[ + [metastore.ListMetadataImportsRequest], + Union[ + metastore.ListMetadataImportsResponse, + Awaitable[metastore.ListMetadataImportsResponse] + ]]: + raise NotImplementedError() + + @property + def get_metadata_import(self) -> Callable[ + [metastore.GetMetadataImportRequest], + Union[ + metastore.MetadataImport, + Awaitable[metastore.MetadataImport] + ]]: + raise NotImplementedError() + + @property + def create_metadata_import(self) -> Callable[ + [metastore.CreateMetadataImportRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_metadata_import(self) -> Callable[ + [metastore.UpdateMetadataImportRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def export_metadata(self) -> Callable[ + [metastore.ExportMetadataRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def restore_service(self) -> Callable[ + [metastore.RestoreServiceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_backups(self) -> Callable[ + [metastore.ListBackupsRequest], + Union[ + metastore.ListBackupsResponse, + Awaitable[metastore.ListBackupsResponse] + ]]: + raise NotImplementedError() + + @property + def get_backup(self) -> Callable[ + [metastore.GetBackupRequest], + Union[ + metastore.Backup, + Awaitable[metastore.Backup] + ]]: + raise NotImplementedError() + + @property + def create_backup(self) -> Callable[ + [metastore.CreateBackupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_backup(self) -> Callable[ + [metastore.DeleteBackupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + 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 delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + 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__ = ( + 'DataprocMetastoreTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/transports/grpc.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/transports/grpc.py new file mode 100644 index 0000000..144df36 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/transports/grpc.py @@ -0,0 +1,845 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1.types import metastore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from .base import DataprocMetastoreTransport, DEFAULT_CLIENT_INFO + + +class DataprocMetastoreGrpcTransport(DataprocMetastoreTransport): + """gRPC backend transport for DataprocMetastore. + + Configures and manages metastore services. Metastore services are + fully managed, highly available, autoscaled, autohealing, OSS-native + deployments of technical metadata management software. Each + metastore service exposes a network endpoint through which metadata + queries are served. Metadata queries can originate from a variety of + sources, including Apache Hive, Apache Presto, and Apache Spark. + + The Dataproc Metastore API defines the following resource model: + + - The service works with a collection of Google Cloud projects, + named: ``/projects/*`` + + - Each project has a collection of available locations, named: + ``/locations/*`` (a location must refer to a Google Cloud + ``region``) + + - Each location has a collection of services, named: + ``/services/*`` + + - Dataproc Metastore services are resources with names of the form: + + ``/projects/{project_number}/locations/{location_id}/services/{service_id}``. + + 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 = 'metastore.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] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + 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 = 'metastore.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 operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_services(self) -> Callable[ + [metastore.ListServicesRequest], + metastore.ListServicesResponse]: + r"""Return a callable for the list services method over gRPC. + + Lists services in a project and location. + + Returns: + Callable[[~.ListServicesRequest], + ~.ListServicesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_services' not in self._stubs: + self._stubs['list_services'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/ListServices', + request_serializer=metastore.ListServicesRequest.serialize, + response_deserializer=metastore.ListServicesResponse.deserialize, + ) + return self._stubs['list_services'] + + @property + def get_service(self) -> Callable[ + [metastore.GetServiceRequest], + metastore.Service]: + r"""Return a callable for the get service method over gRPC. + + Gets the details of a single service. + + Returns: + Callable[[~.GetServiceRequest], + ~.Service]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_service' not in self._stubs: + self._stubs['get_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/GetService', + request_serializer=metastore.GetServiceRequest.serialize, + response_deserializer=metastore.Service.deserialize, + ) + return self._stubs['get_service'] + + @property + def create_service(self) -> Callable[ + [metastore.CreateServiceRequest], + operations_pb2.Operation]: + r"""Return a callable for the create service method over gRPC. + + Creates a metastore service in a project and + location. + + Returns: + Callable[[~.CreateServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_service' not in self._stubs: + self._stubs['create_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/CreateService', + request_serializer=metastore.CreateServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_service'] + + @property + def update_service(self) -> Callable[ + [metastore.UpdateServiceRequest], + operations_pb2.Operation]: + r"""Return a callable for the update service method over gRPC. + + Updates the parameters of a single service. + + Returns: + Callable[[~.UpdateServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_service' not in self._stubs: + self._stubs['update_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/UpdateService', + request_serializer=metastore.UpdateServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_service'] + + @property + def delete_service(self) -> Callable[ + [metastore.DeleteServiceRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete service method over gRPC. + + Deletes a single service. + + Returns: + Callable[[~.DeleteServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_service' not in self._stubs: + self._stubs['delete_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/DeleteService', + request_serializer=metastore.DeleteServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_service'] + + @property + def list_metadata_imports(self) -> Callable[ + [metastore.ListMetadataImportsRequest], + metastore.ListMetadataImportsResponse]: + r"""Return a callable for the list metadata imports method over gRPC. + + Lists imports in a service. + + Returns: + Callable[[~.ListMetadataImportsRequest], + ~.ListMetadataImportsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_metadata_imports' not in self._stubs: + self._stubs['list_metadata_imports'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/ListMetadataImports', + request_serializer=metastore.ListMetadataImportsRequest.serialize, + response_deserializer=metastore.ListMetadataImportsResponse.deserialize, + ) + return self._stubs['list_metadata_imports'] + + @property + def get_metadata_import(self) -> Callable[ + [metastore.GetMetadataImportRequest], + metastore.MetadataImport]: + r"""Return a callable for the get metadata import method over gRPC. + + Gets details of a single import. + + Returns: + Callable[[~.GetMetadataImportRequest], + ~.MetadataImport]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_metadata_import' not in self._stubs: + self._stubs['get_metadata_import'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/GetMetadataImport', + request_serializer=metastore.GetMetadataImportRequest.serialize, + response_deserializer=metastore.MetadataImport.deserialize, + ) + return self._stubs['get_metadata_import'] + + @property + def create_metadata_import(self) -> Callable[ + [metastore.CreateMetadataImportRequest], + operations_pb2.Operation]: + r"""Return a callable for the create metadata import method over gRPC. + + Creates a new MetadataImport in a given project and + location. + + Returns: + Callable[[~.CreateMetadataImportRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_metadata_import' not in self._stubs: + self._stubs['create_metadata_import'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/CreateMetadataImport', + request_serializer=metastore.CreateMetadataImportRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_metadata_import'] + + @property + def update_metadata_import(self) -> Callable[ + [metastore.UpdateMetadataImportRequest], + operations_pb2.Operation]: + r"""Return a callable for the update metadata import method over gRPC. + + Updates a single import. + Only the description field of MetadataImport is + supported to be updated. + + Returns: + Callable[[~.UpdateMetadataImportRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_metadata_import' not in self._stubs: + self._stubs['update_metadata_import'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/UpdateMetadataImport', + request_serializer=metastore.UpdateMetadataImportRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_metadata_import'] + + @property + def export_metadata(self) -> Callable[ + [metastore.ExportMetadataRequest], + operations_pb2.Operation]: + r"""Return a callable for the export metadata method over gRPC. + + Exports metadata from a service. + + Returns: + Callable[[~.ExportMetadataRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_metadata' not in self._stubs: + self._stubs['export_metadata'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/ExportMetadata', + request_serializer=metastore.ExportMetadataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_metadata'] + + @property + def restore_service(self) -> Callable[ + [metastore.RestoreServiceRequest], + operations_pb2.Operation]: + r"""Return a callable for the restore service method over gRPC. + + Restores a service from a backup. + + Returns: + Callable[[~.RestoreServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'restore_service' not in self._stubs: + self._stubs['restore_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/RestoreService', + request_serializer=metastore.RestoreServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_service'] + + @property + def list_backups(self) -> Callable[ + [metastore.ListBackupsRequest], + metastore.ListBackupsResponse]: + r"""Return a callable for the list backups method over gRPC. + + Lists backups in a service. + + Returns: + Callable[[~.ListBackupsRequest], + ~.ListBackupsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_backups' not in self._stubs: + self._stubs['list_backups'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/ListBackups', + request_serializer=metastore.ListBackupsRequest.serialize, + response_deserializer=metastore.ListBackupsResponse.deserialize, + ) + return self._stubs['list_backups'] + + @property + def get_backup(self) -> Callable[ + [metastore.GetBackupRequest], + metastore.Backup]: + r"""Return a callable for the get backup method over gRPC. + + Gets details of a single backup. + + Returns: + Callable[[~.GetBackupRequest], + ~.Backup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_backup' not in self._stubs: + self._stubs['get_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/GetBackup', + request_serializer=metastore.GetBackupRequest.serialize, + response_deserializer=metastore.Backup.deserialize, + ) + return self._stubs['get_backup'] + + @property + def create_backup(self) -> Callable[ + [metastore.CreateBackupRequest], + operations_pb2.Operation]: + r"""Return a callable for the create backup method over gRPC. + + Creates a new backup in a given project and location. + + Returns: + Callable[[~.CreateBackupRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_backup' not in self._stubs: + self._stubs['create_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/CreateBackup', + request_serializer=metastore.CreateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_backup'] + + @property + def delete_backup(self) -> Callable[ + [metastore.DeleteBackupRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete backup method over gRPC. + + Deletes a single backup. + + Returns: + Callable[[~.DeleteBackupRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_backup' not in self._stubs: + self._stubs['delete_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/DeleteBackup', + request_serializer=metastore.DeleteBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_backup'] + + 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 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 set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'DataprocMetastoreGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/transports/grpc_asyncio.py new file mode 100644 index 0000000..cadb545 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/transports/grpc_asyncio.py @@ -0,0 +1,844 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1.types import metastore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from .base import DataprocMetastoreTransport, DEFAULT_CLIENT_INFO +from .grpc import DataprocMetastoreGrpcTransport + + +class DataprocMetastoreGrpcAsyncIOTransport(DataprocMetastoreTransport): + """gRPC AsyncIO backend transport for DataprocMetastore. + + Configures and manages metastore services. Metastore services are + fully managed, highly available, autoscaled, autohealing, OSS-native + deployments of technical metadata management software. Each + metastore service exposes a network endpoint through which metadata + queries are served. Metadata queries can originate from a variety of + sources, including Apache Hive, Apache Presto, and Apache Spark. + + The Dataproc Metastore API defines the following resource model: + + - The service works with a collection of Google Cloud projects, + named: ``/projects/*`` + + - Each project has a collection of available locations, named: + ``/locations/*`` (a location must refer to a Google Cloud + ``region``) + + - Each location has a collection of services, named: + ``/services/*`` + + - Dataproc Metastore services are resources with names of the form: + + ``/projects/{project_number}/locations/{location_id}/services/{service_id}``. + + 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 = 'metastore.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 = 'metastore.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] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + 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 operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_services(self) -> Callable[ + [metastore.ListServicesRequest], + Awaitable[metastore.ListServicesResponse]]: + r"""Return a callable for the list services method over gRPC. + + Lists services in a project and location. + + Returns: + Callable[[~.ListServicesRequest], + Awaitable[~.ListServicesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_services' not in self._stubs: + self._stubs['list_services'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/ListServices', + request_serializer=metastore.ListServicesRequest.serialize, + response_deserializer=metastore.ListServicesResponse.deserialize, + ) + return self._stubs['list_services'] + + @property + def get_service(self) -> Callable[ + [metastore.GetServiceRequest], + Awaitable[metastore.Service]]: + r"""Return a callable for the get service method over gRPC. + + Gets the details of a single service. + + Returns: + Callable[[~.GetServiceRequest], + Awaitable[~.Service]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_service' not in self._stubs: + self._stubs['get_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/GetService', + request_serializer=metastore.GetServiceRequest.serialize, + response_deserializer=metastore.Service.deserialize, + ) + return self._stubs['get_service'] + + @property + def create_service(self) -> Callable[ + [metastore.CreateServiceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create service method over gRPC. + + Creates a metastore service in a project and + location. + + Returns: + Callable[[~.CreateServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_service' not in self._stubs: + self._stubs['create_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/CreateService', + request_serializer=metastore.CreateServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_service'] + + @property + def update_service(self) -> Callable[ + [metastore.UpdateServiceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update service method over gRPC. + + Updates the parameters of a single service. + + Returns: + Callable[[~.UpdateServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_service' not in self._stubs: + self._stubs['update_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/UpdateService', + request_serializer=metastore.UpdateServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_service'] + + @property + def delete_service(self) -> Callable[ + [metastore.DeleteServiceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete service method over gRPC. + + Deletes a single service. + + Returns: + Callable[[~.DeleteServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_service' not in self._stubs: + self._stubs['delete_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/DeleteService', + request_serializer=metastore.DeleteServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_service'] + + @property + def list_metadata_imports(self) -> Callable[ + [metastore.ListMetadataImportsRequest], + Awaitable[metastore.ListMetadataImportsResponse]]: + r"""Return a callable for the list metadata imports method over gRPC. + + Lists imports in a service. + + Returns: + Callable[[~.ListMetadataImportsRequest], + Awaitable[~.ListMetadataImportsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_metadata_imports' not in self._stubs: + self._stubs['list_metadata_imports'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/ListMetadataImports', + request_serializer=metastore.ListMetadataImportsRequest.serialize, + response_deserializer=metastore.ListMetadataImportsResponse.deserialize, + ) + return self._stubs['list_metadata_imports'] + + @property + def get_metadata_import(self) -> Callable[ + [metastore.GetMetadataImportRequest], + Awaitable[metastore.MetadataImport]]: + r"""Return a callable for the get metadata import method over gRPC. + + Gets details of a single import. + + Returns: + Callable[[~.GetMetadataImportRequest], + Awaitable[~.MetadataImport]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_metadata_import' not in self._stubs: + self._stubs['get_metadata_import'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/GetMetadataImport', + request_serializer=metastore.GetMetadataImportRequest.serialize, + response_deserializer=metastore.MetadataImport.deserialize, + ) + return self._stubs['get_metadata_import'] + + @property + def create_metadata_import(self) -> Callable[ + [metastore.CreateMetadataImportRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create metadata import method over gRPC. + + Creates a new MetadataImport in a given project and + location. + + Returns: + Callable[[~.CreateMetadataImportRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_metadata_import' not in self._stubs: + self._stubs['create_metadata_import'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/CreateMetadataImport', + request_serializer=metastore.CreateMetadataImportRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_metadata_import'] + + @property + def update_metadata_import(self) -> Callable[ + [metastore.UpdateMetadataImportRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update metadata import method over gRPC. + + Updates a single import. + Only the description field of MetadataImport is + supported to be updated. + + Returns: + Callable[[~.UpdateMetadataImportRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_metadata_import' not in self._stubs: + self._stubs['update_metadata_import'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/UpdateMetadataImport', + request_serializer=metastore.UpdateMetadataImportRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_metadata_import'] + + @property + def export_metadata(self) -> Callable[ + [metastore.ExportMetadataRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the export metadata method over gRPC. + + Exports metadata from a service. + + Returns: + Callable[[~.ExportMetadataRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_metadata' not in self._stubs: + self._stubs['export_metadata'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/ExportMetadata', + request_serializer=metastore.ExportMetadataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_metadata'] + + @property + def restore_service(self) -> Callable[ + [metastore.RestoreServiceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the restore service method over gRPC. + + Restores a service from a backup. + + Returns: + Callable[[~.RestoreServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'restore_service' not in self._stubs: + self._stubs['restore_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/RestoreService', + request_serializer=metastore.RestoreServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_service'] + + @property + def list_backups(self) -> Callable[ + [metastore.ListBackupsRequest], + Awaitable[metastore.ListBackupsResponse]]: + r"""Return a callable for the list backups method over gRPC. + + Lists backups in a service. + + Returns: + Callable[[~.ListBackupsRequest], + Awaitable[~.ListBackupsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_backups' not in self._stubs: + self._stubs['list_backups'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/ListBackups', + request_serializer=metastore.ListBackupsRequest.serialize, + response_deserializer=metastore.ListBackupsResponse.deserialize, + ) + return self._stubs['list_backups'] + + @property + def get_backup(self) -> Callable[ + [metastore.GetBackupRequest], + Awaitable[metastore.Backup]]: + r"""Return a callable for the get backup method over gRPC. + + Gets details of a single backup. + + Returns: + Callable[[~.GetBackupRequest], + Awaitable[~.Backup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_backup' not in self._stubs: + self._stubs['get_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/GetBackup', + request_serializer=metastore.GetBackupRequest.serialize, + response_deserializer=metastore.Backup.deserialize, + ) + return self._stubs['get_backup'] + + @property + def create_backup(self) -> Callable[ + [metastore.CreateBackupRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create backup method over gRPC. + + Creates a new backup in a given project and location. + + Returns: + Callable[[~.CreateBackupRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_backup' not in self._stubs: + self._stubs['create_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/CreateBackup', + request_serializer=metastore.CreateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_backup'] + + @property + def delete_backup(self) -> Callable[ + [metastore.DeleteBackupRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete backup method over gRPC. + + Deletes a single backup. + + Returns: + Callable[[~.DeleteBackupRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_backup' not in self._stubs: + self._stubs['delete_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastore/DeleteBackup', + request_serializer=metastore.DeleteBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_backup'] + + 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 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 set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'DataprocMetastoreGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/transports/rest.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/transports/rest.py new file mode 100644 index 0000000..4b65fce --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore/transports/rest.py @@ -0,0 +1,2699 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +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.metastore_v1.types import metastore +from google.longrunning import operations_pb2 # type: ignore + +from .base import DataprocMetastoreTransport, 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 DataprocMetastoreRestInterceptor: + """Interceptor for DataprocMetastore. + + 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 DataprocMetastoreRestTransport. + + .. code-block:: python + class MyCustomDataprocMetastoreInterceptor(DataprocMetastoreRestInterceptor): + def pre_create_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_metadata_import(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_metadata_import(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_export_metadata(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_export_metadata(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_metadata_import(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_metadata_import(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_backups(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_backups(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_metadata_imports(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_metadata_imports(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_services(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_services(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_restore_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_restore_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_metadata_import(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_metadata_import(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_service(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DataprocMetastoreRestTransport(interceptor=MyCustomDataprocMetastoreInterceptor()) + client = DataprocMetastoreClient(transport=transport) + + + """ + def pre_create_backup(self, request: metastore.CreateBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.CreateBackupRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_create_backup(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_backup + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_create_metadata_import(self, request: metastore.CreateMetadataImportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.CreateMetadataImportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_metadata_import + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_create_metadata_import(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_metadata_import + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_create_service(self, request: metastore.CreateServiceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.CreateServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_create_service(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_service + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_delete_backup(self, request: metastore.DeleteBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.DeleteBackupRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_delete_backup(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_backup + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_delete_service(self, request: metastore.DeleteServiceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.DeleteServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_delete_service(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_service + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_export_metadata(self, request: metastore.ExportMetadataRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.ExportMetadataRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for export_metadata + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_export_metadata(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for export_metadata + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_get_backup(self, request: metastore.GetBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.GetBackupRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_get_backup(self, response: metastore.Backup) -> metastore.Backup: + """Post-rpc interceptor for get_backup + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_get_metadata_import(self, request: metastore.GetMetadataImportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.GetMetadataImportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_metadata_import + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_get_metadata_import(self, response: metastore.MetadataImport) -> metastore.MetadataImport: + """Post-rpc interceptor for get_metadata_import + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_get_service(self, request: metastore.GetServiceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.GetServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_get_service(self, response: metastore.Service) -> metastore.Service: + """Post-rpc interceptor for get_service + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_list_backups(self, request: metastore.ListBackupsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.ListBackupsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_backups + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_list_backups(self, response: metastore.ListBackupsResponse) -> metastore.ListBackupsResponse: + """Post-rpc interceptor for list_backups + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_list_metadata_imports(self, request: metastore.ListMetadataImportsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.ListMetadataImportsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_metadata_imports + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_list_metadata_imports(self, response: metastore.ListMetadataImportsResponse) -> metastore.ListMetadataImportsResponse: + """Post-rpc interceptor for list_metadata_imports + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_list_services(self, request: metastore.ListServicesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.ListServicesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_services + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_list_services(self, response: metastore.ListServicesResponse) -> metastore.ListServicesResponse: + """Post-rpc interceptor for list_services + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_restore_service(self, request: metastore.RestoreServiceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.RestoreServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for restore_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_restore_service(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for restore_service + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_update_metadata_import(self, request: metastore.UpdateMetadataImportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.UpdateMetadataImportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_metadata_import + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_update_metadata_import(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_metadata_import + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_update_service(self, request: metastore.UpdateServiceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.UpdateServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_update_service(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_service + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DataprocMetastoreRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DataprocMetastoreRestInterceptor + + +class DataprocMetastoreRestTransport(DataprocMetastoreTransport): + """REST backend transport for DataprocMetastore. + + Configures and manages metastore services. Metastore services are + fully managed, highly available, autoscaled, autohealing, OSS-native + deployments of technical metadata management software. Each + metastore service exposes a network endpoint through which metadata + queries are served. Metadata queries can originate from a variety of + sources, including Apache Hive, Apache Presto, and Apache Spark. + + The Dataproc Metastore API defines the following resource model: + + - The service works with a collection of Google Cloud projects, + named: ``/projects/*`` + + - Each project has a collection of available locations, named: + ``/locations/*`` (a location must refer to a Google Cloud + ``region``) + + - Each location has a collection of services, named: + ``/services/*`` + + - Dataproc Metastore services are resources with names of the form: + + ``/projects/{project_number}/locations/{location_id}/services/{service_id}``. + + 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 = 'metastore.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[DataprocMetastoreRestInterceptor] = 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) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DataprocMetastoreRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateBackup(DataprocMetastoreRestStub): + def __hash__(self): + return hash("CreateBackup") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "backupId" : "", } + + @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: metastore.CreateBackupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create backup method over HTTP. + + Args: + request (~.metastore.CreateBackupRequest): + The request object. Request message for + [DataprocMetastore.CreateBackup][google.cloud.metastore.v1.DataprocMetastore.CreateBackup]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/services/*}/backups', + 'body': 'backup', + }, + ] + request, metadata = self._interceptor.pre_create_backup(request, metadata) + pb_request = metastore.CreateBackupRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_backup(resp) + return resp + + class _CreateMetadataImport(DataprocMetastoreRestStub): + def __hash__(self): + return hash("CreateMetadataImport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "metadataImportId" : "", } + + @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: metastore.CreateMetadataImportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create metadata import method over HTTP. + + Args: + request (~.metastore.CreateMetadataImportRequest): + The request object. Request message for + [DataprocMetastore.CreateMetadataImport][google.cloud.metastore.v1.DataprocMetastore.CreateMetadataImport]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/services/*}/metadataImports', + 'body': 'metadata_import', + }, + ] + request, metadata = self._interceptor.pre_create_metadata_import(request, metadata) + pb_request = metastore.CreateMetadataImportRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_metadata_import(resp) + return resp + + class _CreateService(DataprocMetastoreRestStub): + def __hash__(self): + return hash("CreateService") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "serviceId" : "", } + + @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: metastore.CreateServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create service method over HTTP. + + Args: + request (~.metastore.CreateServiceRequest): + The request object. Request message for + [DataprocMetastore.CreateService][google.cloud.metastore.v1.DataprocMetastore.CreateService]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/services', + 'body': 'service', + }, + ] + request, metadata = self._interceptor.pre_create_service(request, metadata) + pb_request = metastore.CreateServiceRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_service(resp) + return resp + + class _DeleteBackup(DataprocMetastoreRestStub): + def __hash__(self): + return hash("DeleteBackup") + + __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: metastore.DeleteBackupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete backup method over HTTP. + + Args: + request (~.metastore.DeleteBackupRequest): + The request object. Request message for + [DataprocMetastore.DeleteBackup][google.cloud.metastore.v1.DataprocMetastore.DeleteBackup]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/services/*/backups/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_backup(request, metadata) + pb_request = metastore.DeleteBackupRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_backup(resp) + return resp + + class _DeleteService(DataprocMetastoreRestStub): + def __hash__(self): + return hash("DeleteService") + + __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: metastore.DeleteServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete service method over HTTP. + + Args: + request (~.metastore.DeleteServiceRequest): + The request object. Request message for + [DataprocMetastore.DeleteService][google.cloud.metastore.v1.DataprocMetastore.DeleteService]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/services/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_service(request, metadata) + pb_request = metastore.DeleteServiceRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_service(resp) + return resp + + class _ExportMetadata(DataprocMetastoreRestStub): + def __hash__(self): + return hash("ExportMetadata") + + __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: metastore.ExportMetadataRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the export metadata method over HTTP. + + Args: + request (~.metastore.ExportMetadataRequest): + The request object. Request message for + [DataprocMetastore.ExportMetadata][google.cloud.metastore.v1.DataprocMetastore.ExportMetadata]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{service=projects/*/locations/*/services/*}:exportMetadata', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_export_metadata(request, metadata) + pb_request = metastore.ExportMetadataRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_export_metadata(resp) + return resp + + class _GetBackup(DataprocMetastoreRestStub): + def __hash__(self): + return hash("GetBackup") + + __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: metastore.GetBackupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.Backup: + r"""Call the get backup method over HTTP. + + Args: + request (~.metastore.GetBackupRequest): + The request object. Request message for + [DataprocMetastore.GetBackup][google.cloud.metastore.v1.DataprocMetastore.GetBackup]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.Backup: + The details of a backup resource. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/services/*/backups/*}', + }, + ] + request, metadata = self._interceptor.pre_get_backup(request, metadata) + pb_request = metastore.GetBackupRequest.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 = metastore.Backup() + pb_resp = metastore.Backup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_backup(resp) + return resp + + class _GetMetadataImport(DataprocMetastoreRestStub): + def __hash__(self): + return hash("GetMetadataImport") + + __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: metastore.GetMetadataImportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.MetadataImport: + r"""Call the get metadata import method over HTTP. + + Args: + request (~.metastore.GetMetadataImportRequest): + The request object. Request message for + [DataprocMetastore.GetMetadataImport][google.cloud.metastore.v1.DataprocMetastore.GetMetadataImport]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.MetadataImport: + A metastore resource that imports + metadata. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/services/*/metadataImports/*}', + }, + ] + request, metadata = self._interceptor.pre_get_metadata_import(request, metadata) + pb_request = metastore.GetMetadataImportRequest.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 = metastore.MetadataImport() + pb_resp = metastore.MetadataImport.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_metadata_import(resp) + return resp + + class _GetService(DataprocMetastoreRestStub): + def __hash__(self): + return hash("GetService") + + __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: metastore.GetServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.Service: + r"""Call the get service method over HTTP. + + Args: + request (~.metastore.GetServiceRequest): + The request object. Request message for + [DataprocMetastore.GetService][google.cloud.metastore.v1.DataprocMetastore.GetService]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.Service: + A managed metastore service that + serves metadata queries. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/services/*}', + }, + ] + request, metadata = self._interceptor.pre_get_service(request, metadata) + pb_request = metastore.GetServiceRequest.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 = metastore.Service() + pb_resp = metastore.Service.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_service(resp) + return resp + + class _ListBackups(DataprocMetastoreRestStub): + def __hash__(self): + return hash("ListBackups") + + __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: metastore.ListBackupsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.ListBackupsResponse: + r"""Call the list backups method over HTTP. + + Args: + request (~.metastore.ListBackupsRequest): + The request object. Request message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1.DataprocMetastore.ListBackups]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.ListBackupsResponse: + Response message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1.DataprocMetastore.ListBackups]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/services/*}/backups', + }, + ] + request, metadata = self._interceptor.pre_list_backups(request, metadata) + pb_request = metastore.ListBackupsRequest.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 = metastore.ListBackupsResponse() + pb_resp = metastore.ListBackupsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_backups(resp) + return resp + + class _ListMetadataImports(DataprocMetastoreRestStub): + def __hash__(self): + return hash("ListMetadataImports") + + __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: metastore.ListMetadataImportsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.ListMetadataImportsResponse: + r"""Call the list metadata imports method over HTTP. + + Args: + request (~.metastore.ListMetadataImportsRequest): + The request object. Request message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1.DataprocMetastore.ListMetadataImports]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.ListMetadataImportsResponse: + Response message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1.DataprocMetastore.ListMetadataImports]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/services/*}/metadataImports', + }, + ] + request, metadata = self._interceptor.pre_list_metadata_imports(request, metadata) + pb_request = metastore.ListMetadataImportsRequest.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 = metastore.ListMetadataImportsResponse() + pb_resp = metastore.ListMetadataImportsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_metadata_imports(resp) + return resp + + class _ListServices(DataprocMetastoreRestStub): + def __hash__(self): + return hash("ListServices") + + __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: metastore.ListServicesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.ListServicesResponse: + r"""Call the list services method over HTTP. + + Args: + request (~.metastore.ListServicesRequest): + The request object. Request message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1.DataprocMetastore.ListServices]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.ListServicesResponse: + Response message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1.DataprocMetastore.ListServices]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/services', + }, + ] + request, metadata = self._interceptor.pre_list_services(request, metadata) + pb_request = metastore.ListServicesRequest.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 = metastore.ListServicesResponse() + pb_resp = metastore.ListServicesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_services(resp) + return resp + + class _RestoreService(DataprocMetastoreRestStub): + def __hash__(self): + return hash("RestoreService") + + __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: metastore.RestoreServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the restore service method over HTTP. + + Args: + request (~.metastore.RestoreServiceRequest): + The request object. Request message for [DataprocMetastore.Restore][]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{service=projects/*/locations/*/services/*}:restore', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_restore_service(request, metadata) + pb_request = metastore.RestoreServiceRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_restore_service(resp) + return resp + + class _UpdateMetadataImport(DataprocMetastoreRestStub): + def __hash__(self): + return hash("UpdateMetadataImport") + + __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: metastore.UpdateMetadataImportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update metadata import method over HTTP. + + Args: + request (~.metastore.UpdateMetadataImportRequest): + The request object. Request message for + [DataprocMetastore.UpdateMetadataImport][google.cloud.metastore.v1.DataprocMetastore.UpdateMetadataImport]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{metadata_import.name=projects/*/locations/*/services/*/metadataImports/*}', + 'body': 'metadata_import', + }, + ] + request, metadata = self._interceptor.pre_update_metadata_import(request, metadata) + pb_request = metastore.UpdateMetadataImportRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_metadata_import(resp) + return resp + + class _UpdateService(DataprocMetastoreRestStub): + def __hash__(self): + return hash("UpdateService") + + __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: metastore.UpdateServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update service method over HTTP. + + Args: + request (~.metastore.UpdateServiceRequest): + The request object. Request message for + [DataprocMetastore.UpdateService][google.cloud.metastore.v1.DataprocMetastore.UpdateService]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{service.name=projects/*/locations/*/services/*}', + 'body': 'service', + }, + ] + request, metadata = self._interceptor.pre_update_service(request, metadata) + pb_request = metastore.UpdateServiceRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_service(resp) + return resp + + @property + def create_backup(self) -> Callable[ + [metastore.CreateBackupRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_metadata_import(self) -> Callable[ + [metastore.CreateMetadataImportRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateMetadataImport(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_service(self) -> Callable[ + [metastore.CreateServiceRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateService(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_backup(self) -> Callable[ + [metastore.DeleteBackupRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_service(self) -> Callable[ + [metastore.DeleteServiceRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteService(self._session, self._host, self._interceptor) # type: ignore + + @property + def export_metadata(self) -> Callable[ + [metastore.ExportMetadataRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ExportMetadata(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_backup(self) -> Callable[ + [metastore.GetBackupRequest], + metastore.Backup]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_metadata_import(self) -> Callable[ + [metastore.GetMetadataImportRequest], + metastore.MetadataImport]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetMetadataImport(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_service(self) -> Callable[ + [metastore.GetServiceRequest], + metastore.Service]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetService(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_backups(self) -> Callable[ + [metastore.ListBackupsRequest], + metastore.ListBackupsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListBackups(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_metadata_imports(self) -> Callable[ + [metastore.ListMetadataImportsRequest], + metastore.ListMetadataImportsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListMetadataImports(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_services(self) -> Callable[ + [metastore.ListServicesRequest], + metastore.ListServicesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListServices(self._session, self._host, self._interceptor) # type: ignore + + @property + def restore_service(self) -> Callable[ + [metastore.RestoreServiceRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RestoreService(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_metadata_import(self) -> Callable[ + [metastore.UpdateMetadataImportRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMetadataImport(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_service(self) -> Callable[ + [metastore.UpdateServiceRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateService(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(DataprocMetastoreRestStub): + 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(DataprocMetastoreRestStub): + 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 get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(DataprocMetastoreRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy 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: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/services/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/services/*/backups/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/federations/*}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(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 = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(DataprocMetastoreRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy 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: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/services/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/services/*/backups/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/federations/*}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.loads(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) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(DataprocMetastoreRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions 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: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/services/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/federations/*}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.loads(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) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(DataprocMetastoreRestStub): + 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(DataprocMetastoreRestStub): + 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(DataprocMetastoreRestStub): + 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__=( + 'DataprocMetastoreRestTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/__init__.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/__init__.py new file mode 100644 index 0000000..7029be0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import DataprocMetastoreFederationClient +from .async_client import DataprocMetastoreFederationAsyncClient + +__all__ = ( + 'DataprocMetastoreFederationClient', + 'DataprocMetastoreFederationAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/async_client.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/async_client.py new file mode 100644 index 0000000..8d6aa7d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/async_client.py @@ -0,0 +1,1388 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.metastore_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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1.services.dataproc_metastore_federation import pagers +from google.cloud.metastore_v1.types import metastore +from google.cloud.metastore_v1.types import metastore_federation +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DataprocMetastoreFederationTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DataprocMetastoreFederationGrpcAsyncIOTransport +from .client import DataprocMetastoreFederationClient + + +class DataprocMetastoreFederationAsyncClient: + """Configures and manages metastore federation services. Dataproc + Metastore Federation Service allows federating a collection of + backend metastores like BigQuery, Dataplex Lakes, and other Dataproc + Metastores. The Federation Service exposes a gRPC URL through which + metadata from the backend metastores are served at query time. + + The Dataproc Metastore Federation API defines the following resource + model: + + - The service works with a collection of Google Cloud projects. + - Each project has a collection of available locations. + - Each location has a collection of federations. + - Dataproc Metastore Federations are resources with names of the + form: + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + """ + + _client: DataprocMetastoreFederationClient + + DEFAULT_ENDPOINT = DataprocMetastoreFederationClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DataprocMetastoreFederationClient.DEFAULT_MTLS_ENDPOINT + + federation_path = staticmethod(DataprocMetastoreFederationClient.federation_path) + parse_federation_path = staticmethod(DataprocMetastoreFederationClient.parse_federation_path) + common_billing_account_path = staticmethod(DataprocMetastoreFederationClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DataprocMetastoreFederationClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DataprocMetastoreFederationClient.common_folder_path) + parse_common_folder_path = staticmethod(DataprocMetastoreFederationClient.parse_common_folder_path) + common_organization_path = staticmethod(DataprocMetastoreFederationClient.common_organization_path) + parse_common_organization_path = staticmethod(DataprocMetastoreFederationClient.parse_common_organization_path) + common_project_path = staticmethod(DataprocMetastoreFederationClient.common_project_path) + parse_common_project_path = staticmethod(DataprocMetastoreFederationClient.parse_common_project_path) + common_location_path = staticmethod(DataprocMetastoreFederationClient.common_location_path) + parse_common_location_path = staticmethod(DataprocMetastoreFederationClient.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: + DataprocMetastoreFederationAsyncClient: The constructed client. + """ + return DataprocMetastoreFederationClient.from_service_account_info.__func__(DataprocMetastoreFederationAsyncClient, 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: + DataprocMetastoreFederationAsyncClient: The constructed client. + """ + return DataprocMetastoreFederationClient.from_service_account_file.__func__(DataprocMetastoreFederationAsyncClient, 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 DataprocMetastoreFederationClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DataprocMetastoreFederationTransport: + """Returns the transport used by the client instance. + + Returns: + DataprocMetastoreFederationTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DataprocMetastoreFederationClient).get_transport_class, type(DataprocMetastoreFederationClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DataprocMetastoreFederationTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dataproc metastore federation 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, ~.DataprocMetastoreFederationTransport]): 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 = DataprocMetastoreFederationClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_federations(self, + request: Optional[Union[metastore_federation.ListFederationsRequest, 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.ListFederationsAsyncPager: + r"""Lists federations in a 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 metastore_v1 + + async def sample_list_federations(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.ListFederationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_federations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.ListFederationsRequest, dict]]): + The request object. Request message for ListFederations. + parent (:class:`str`): + Required. The relative resource name of the location of + metastore federations to list, in the following form: + ``projects/{project_number}/locations/{location_id}``. + + 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.metastore_v1.services.dataproc_metastore_federation.pagers.ListFederationsAsyncPager: + Response message for ListFederations + 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 = metastore_federation.ListFederationsRequest(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_federations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListFederationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_federation(self, + request: Optional[Union[metastore_federation.GetFederationRequest, 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]] = (), + ) -> metastore_federation.Federation: + r"""Gets the details of a single federation. + + .. 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 metastore_v1 + + async def sample_get_federation(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.GetFederationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_federation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.GetFederationRequest, dict]]): + The request object. Request message for GetFederation. + name (:class:`str`): + Required. The relative resource name of the metastore + federation to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + 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.metastore_v1.types.Federation: + Represents a federation of multiple + backend metastores. + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 = metastore_federation.GetFederationRequest(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_federation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_federation(self, + request: Optional[Union[metastore_federation.CreateFederationRequest, dict]] = None, + *, + parent: Optional[str] = None, + federation: Optional[metastore_federation.Federation] = None, + federation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a metastore federation in a 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 metastore_v1 + + async def sample_create_federation(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.CreateFederationRequest( + parent="parent_value", + federation_id="federation_id_value", + ) + + # Make the request + operation = client.create_federation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.CreateFederationRequest, dict]]): + The request object. Request message for CreateFederation. + parent (:class:`str`): + Required. The relative resource name of the location in + which to create a federation service, in the following + form: + + ``projects/{project_number}/locations/{location_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + federation (:class:`google.cloud.metastore_v1.types.Federation`): + Required. The Metastore Federation to create. The + ``name`` field is ignored. The ID of the created + metastore federation must be provided in the request's + ``federation_id`` field. + + This corresponds to the ``federation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + federation_id (:class:`str`): + Required. The ID of the metastore + federation, which is used as the final + component of the metastore federation's + name. + This value must be between 2 and 63 + characters long inclusive, begin with a + letter, end with a letter or number, and + consist of alpha-numeric ASCII + characters or hyphens. + + This corresponds to the ``federation_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1.types.Federation` + Represents a federation of multiple backend metastores. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, federation, federation_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = metastore_federation.CreateFederationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if federation is not None: + request.federation = federation + if federation_id is not None: + request.federation_id = federation_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_federation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore_federation.Federation, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_federation(self, + request: Optional[Union[metastore_federation.UpdateFederationRequest, dict]] = None, + *, + federation: Optional[metastore_federation.Federation] = 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the fields of a federation. + + .. 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 metastore_v1 + + async def sample_update_federation(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.UpdateFederationRequest( + ) + + # Make the request + operation = client.update_federation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.UpdateFederationRequest, dict]]): + The request object. Request message for UpdateFederation. + federation (:class:`google.cloud.metastore_v1.types.Federation`): + Required. The metastore federation to update. The server + only merges fields in the service if they are specified + in ``update_mask``. + + The metastore federation's ``name`` field is used to + identify the metastore service to be updated. + + This corresponds to the ``federation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. A field mask used to specify the fields to be + overwritten in the metastore federation resource by the + update. Fields specified in the ``update_mask`` are + relative to the resource (not to the full request). A + field is overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1.types.Federation` + Represents a federation of multiple backend metastores. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([federation, 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 = metastore_federation.UpdateFederationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if federation is not None: + request.federation = federation + 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_federation, + 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(( + ("federation.name", request.federation.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore_federation.Federation, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_federation(self, + request: Optional[Union[metastore_federation.DeleteFederationRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single federation. + + .. 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 metastore_v1 + + async def sample_delete_federation(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.DeleteFederationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_federation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1.types.DeleteFederationRequest, dict]]): + The request object. Request message for DeleteFederation. + name (:class:`str`): + Required. The relative resource name of the metastore + federation to delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 = metastore_federation.DeleteFederationRequest(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_federation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=metastore.OperationMetadata, + ) + + # 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.set_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.GetIamPolicyRequest(**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_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.test_iam_permissions, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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): + 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__ = ( + "DataprocMetastoreFederationAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/client.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/client.py new file mode 100644 index 0000000..545a056 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/client.py @@ -0,0 +1,1587 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.metastore_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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1.services.dataproc_metastore_federation import pagers +from google.cloud.metastore_v1.types import metastore +from google.cloud.metastore_v1.types import metastore_federation +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DataprocMetastoreFederationTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DataprocMetastoreFederationGrpcTransport +from .transports.grpc_asyncio import DataprocMetastoreFederationGrpcAsyncIOTransport +from .transports.rest import DataprocMetastoreFederationRestTransport + + +class DataprocMetastoreFederationClientMeta(type): + """Metaclass for the DataprocMetastoreFederation 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[DataprocMetastoreFederationTransport]] + _transport_registry["grpc"] = DataprocMetastoreFederationGrpcTransport + _transport_registry["grpc_asyncio"] = DataprocMetastoreFederationGrpcAsyncIOTransport + _transport_registry["rest"] = DataprocMetastoreFederationRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[DataprocMetastoreFederationTransport]: + """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 DataprocMetastoreFederationClient(metaclass=DataprocMetastoreFederationClientMeta): + """Configures and manages metastore federation services. Dataproc + Metastore Federation Service allows federating a collection of + backend metastores like BigQuery, Dataplex Lakes, and other Dataproc + Metastores. The Federation Service exposes a gRPC URL through which + metadata from the backend metastores are served at query time. + + The Dataproc Metastore Federation API defines the following resource + model: + + - The service works with a collection of Google Cloud projects. + - Each project has a collection of available locations. + - Each location has a collection of federations. + - Dataproc Metastore Federations are resources with names of the + form: + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + """ + + @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 = "metastore.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: + DataprocMetastoreFederationClient: 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: + DataprocMetastoreFederationClient: 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) -> DataprocMetastoreFederationTransport: + """Returns the transport used by the client instance. + + Returns: + DataprocMetastoreFederationTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def federation_path(project: str,location: str,federation: str,) -> str: + """Returns a fully-qualified federation string.""" + return "projects/{project}/locations/{location}/federations/{federation}".format(project=project, location=location, federation=federation, ) + + @staticmethod + def parse_federation_path(path: str) -> Dict[str,str]: + """Parses a federation path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/federations/(?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, DataprocMetastoreFederationTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dataproc metastore federation 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, DataprocMetastoreFederationTransport]): 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, DataprocMetastoreFederationTransport): + # transport is a DataprocMetastoreFederationTransport 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_federations(self, + request: Optional[Union[metastore_federation.ListFederationsRequest, 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.ListFederationsPager: + r"""Lists federations in a 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 metastore_v1 + + def sample_list_federations(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1.ListFederationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_federations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.ListFederationsRequest, dict]): + The request object. Request message for ListFederations. + parent (str): + Required. The relative resource name of the location of + metastore federations to list, in the following form: + ``projects/{project_number}/locations/{location_id}``. + + 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.metastore_v1.services.dataproc_metastore_federation.pagers.ListFederationsPager: + Response message for ListFederations + 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 metastore_federation.ListFederationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore_federation.ListFederationsRequest): + request = metastore_federation.ListFederationsRequest(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_federations] + + # Certain 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.ListFederationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_federation(self, + request: Optional[Union[metastore_federation.GetFederationRequest, 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]] = (), + ) -> metastore_federation.Federation: + r"""Gets the details of a single federation. + + .. 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 metastore_v1 + + def sample_get_federation(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1.GetFederationRequest( + name="name_value", + ) + + # Make the request + response = client.get_federation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.GetFederationRequest, dict]): + The request object. Request message for GetFederation. + name (str): + Required. The relative resource name of the metastore + federation to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + 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.metastore_v1.types.Federation: + Represents a federation of multiple + backend metastores. + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 metastore_federation.GetFederationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore_federation.GetFederationRequest): + request = metastore_federation.GetFederationRequest(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_federation] + + # Certain 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_federation(self, + request: Optional[Union[metastore_federation.CreateFederationRequest, dict]] = None, + *, + parent: Optional[str] = None, + federation: Optional[metastore_federation.Federation] = None, + federation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a metastore federation in a 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 metastore_v1 + + def sample_create_federation(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1.CreateFederationRequest( + parent="parent_value", + federation_id="federation_id_value", + ) + + # Make the request + operation = client.create_federation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.CreateFederationRequest, dict]): + The request object. Request message for CreateFederation. + parent (str): + Required. The relative resource name of the location in + which to create a federation service, in the following + form: + + ``projects/{project_number}/locations/{location_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + federation (google.cloud.metastore_v1.types.Federation): + Required. The Metastore Federation to create. The + ``name`` field is ignored. The ID of the created + metastore federation must be provided in the request's + ``federation_id`` field. + + This corresponds to the ``federation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + federation_id (str): + Required. The ID of the metastore + federation, which is used as the final + component of the metastore federation's + name. + This value must be between 2 and 63 + characters long inclusive, begin with a + letter, end with a letter or number, and + consist of alpha-numeric ASCII + characters or hyphens. + + This corresponds to the ``federation_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1.types.Federation` + Represents a federation of multiple backend metastores. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, federation, federation_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a metastore_federation.CreateFederationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore_federation.CreateFederationRequest): + request = metastore_federation.CreateFederationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if federation is not None: + request.federation = federation + if federation_id is not None: + request.federation_id = federation_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_federation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore_federation.Federation, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_federation(self, + request: Optional[Union[metastore_federation.UpdateFederationRequest, dict]] = None, + *, + federation: Optional[metastore_federation.Federation] = 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]] = (), + ) -> operation.Operation: + r"""Updates the fields of a federation. + + .. 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 metastore_v1 + + def sample_update_federation(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1.UpdateFederationRequest( + ) + + # Make the request + operation = client.update_federation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.UpdateFederationRequest, dict]): + The request object. Request message for UpdateFederation. + federation (google.cloud.metastore_v1.types.Federation): + Required. The metastore federation to update. The server + only merges fields in the service if they are specified + in ``update_mask``. + + The metastore federation's ``name`` field is used to + identify the metastore service to be updated. + + This corresponds to the ``federation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask used to specify the fields to be + overwritten in the metastore federation resource by the + update. Fields specified in the ``update_mask`` are + relative to the resource (not to the full request). A + field is overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1.types.Federation` + Represents a federation of multiple backend metastores. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([federation, 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 metastore_federation.UpdateFederationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore_federation.UpdateFederationRequest): + request = metastore_federation.UpdateFederationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if federation is not None: + request.federation = federation + 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_federation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("federation.name", request.federation.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore_federation.Federation, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_federation(self, + request: Optional[Union[metastore_federation.DeleteFederationRequest, 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]] = (), + ) -> operation.Operation: + r"""Deletes a single federation. + + .. 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 metastore_v1 + + def sample_delete_federation(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1.DeleteFederationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_federation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1.types.DeleteFederationRequest, dict]): + The request object. Request message for DeleteFederation. + name (str): + Required. The relative resource name of the metastore + federation to delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 metastore_federation.DeleteFederationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore_federation.DeleteFederationRequest): + request = metastore_federation.DeleteFederationRequest(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_federation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "DataprocMetastoreFederationClient": + 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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__ = ( + "DataprocMetastoreFederationClient", +) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/pagers.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/pagers.py new file mode 100644 index 0000000..8b6a59f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.metastore_v1.types import metastore_federation + + +class ListFederationsPager: + """A pager for iterating through ``list_federations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1.types.ListFederationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``federations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFederations`` requests and continue to iterate + through the ``federations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1.types.ListFederationsResponse` + 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[..., metastore_federation.ListFederationsResponse], + request: metastore_federation.ListFederationsRequest, + response: metastore_federation.ListFederationsResponse, + *, + 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.metastore_v1.types.ListFederationsRequest): + The initial request object. + response (google.cloud.metastore_v1.types.ListFederationsResponse): + 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 = metastore_federation.ListFederationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[metastore_federation.ListFederationsResponse]: + 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[metastore_federation.Federation]: + for page in self.pages: + yield from page.federations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFederationsAsyncPager: + """A pager for iterating through ``list_federations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1.types.ListFederationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``federations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFederations`` requests and continue to iterate + through the ``federations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1.types.ListFederationsResponse` + 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[metastore_federation.ListFederationsResponse]], + request: metastore_federation.ListFederationsRequest, + response: metastore_federation.ListFederationsResponse, + *, + 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.metastore_v1.types.ListFederationsRequest): + The initial request object. + response (google.cloud.metastore_v1.types.ListFederationsResponse): + 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 = metastore_federation.ListFederationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[metastore_federation.ListFederationsResponse]: + 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[metastore_federation.Federation]: + async def async_generator(): + async for page in self.pages: + for response in page.federations: + 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/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/__init__.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/__init__.py new file mode 100644 index 0000000..0ba9a1b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import DataprocMetastoreFederationTransport +from .grpc import DataprocMetastoreFederationGrpcTransport +from .grpc_asyncio import DataprocMetastoreFederationGrpcAsyncIOTransport +from .rest import DataprocMetastoreFederationRestTransport +from .rest import DataprocMetastoreFederationRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DataprocMetastoreFederationTransport]] +_transport_registry['grpc'] = DataprocMetastoreFederationGrpcTransport +_transport_registry['grpc_asyncio'] = DataprocMetastoreFederationGrpcAsyncIOTransport +_transport_registry['rest'] = DataprocMetastoreFederationRestTransport + +__all__ = ( + 'DataprocMetastoreFederationTransport', + 'DataprocMetastoreFederationGrpcTransport', + 'DataprocMetastoreFederationGrpcAsyncIOTransport', + 'DataprocMetastoreFederationRestTransport', + 'DataprocMetastoreFederationRestInterceptor', +) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/base.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/base.py new file mode 100644 index 0000000..84a5608 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/base.py @@ -0,0 +1,288 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.metastore_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.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1.types import metastore_federation +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class DataprocMetastoreFederationTransport(abc.ABC): + """Abstract transport class for DataprocMetastoreFederation.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'metastore.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_federations: gapic_v1.method.wrap_method( + self.list_federations, + default_timeout=None, + client_info=client_info, + ), + self.get_federation: gapic_v1.method.wrap_method( + self.get_federation, + default_timeout=None, + client_info=client_info, + ), + self.create_federation: gapic_v1.method.wrap_method( + self.create_federation, + default_timeout=None, + client_info=client_info, + ), + self.update_federation: gapic_v1.method.wrap_method( + self.update_federation, + default_timeout=None, + client_info=client_info, + ), + self.delete_federation: gapic_v1.method.wrap_method( + self.delete_federation, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_federations(self) -> Callable[ + [metastore_federation.ListFederationsRequest], + Union[ + metastore_federation.ListFederationsResponse, + Awaitable[metastore_federation.ListFederationsResponse] + ]]: + raise NotImplementedError() + + @property + def get_federation(self) -> Callable[ + [metastore_federation.GetFederationRequest], + Union[ + metastore_federation.Federation, + Awaitable[metastore_federation.Federation] + ]]: + raise NotImplementedError() + + @property + def create_federation(self) -> Callable[ + [metastore_federation.CreateFederationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_federation(self) -> Callable[ + [metastore_federation.UpdateFederationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_federation(self) -> Callable[ + [metastore_federation.DeleteFederationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + 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 delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + 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__ = ( + 'DataprocMetastoreFederationTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/grpc.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/grpc.py new file mode 100644 index 0000000..a4ae809 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/grpc.py @@ -0,0 +1,575 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1.types import metastore_federation +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from .base import DataprocMetastoreFederationTransport, DEFAULT_CLIENT_INFO + + +class DataprocMetastoreFederationGrpcTransport(DataprocMetastoreFederationTransport): + """gRPC backend transport for DataprocMetastoreFederation. + + Configures and manages metastore federation services. Dataproc + Metastore Federation Service allows federating a collection of + backend metastores like BigQuery, Dataplex Lakes, and other Dataproc + Metastores. The Federation Service exposes a gRPC URL through which + metadata from the backend metastores are served at query time. + + The Dataproc Metastore Federation API defines the following resource + model: + + - The service works with a collection of Google Cloud projects. + - Each project has a collection of available locations. + - Each location has a collection of federations. + - Dataproc Metastore Federations are resources with names of the + form: + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + 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 = 'metastore.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] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + 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 = 'metastore.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 operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_federations(self) -> Callable[ + [metastore_federation.ListFederationsRequest], + metastore_federation.ListFederationsResponse]: + r"""Return a callable for the list federations method over gRPC. + + Lists federations in a project and location. + + Returns: + Callable[[~.ListFederationsRequest], + ~.ListFederationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_federations' not in self._stubs: + self._stubs['list_federations'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastoreFederation/ListFederations', + request_serializer=metastore_federation.ListFederationsRequest.serialize, + response_deserializer=metastore_federation.ListFederationsResponse.deserialize, + ) + return self._stubs['list_federations'] + + @property + def get_federation(self) -> Callable[ + [metastore_federation.GetFederationRequest], + metastore_federation.Federation]: + r"""Return a callable for the get federation method over gRPC. + + Gets the details of a single federation. + + Returns: + Callable[[~.GetFederationRequest], + ~.Federation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_federation' not in self._stubs: + self._stubs['get_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastoreFederation/GetFederation', + request_serializer=metastore_federation.GetFederationRequest.serialize, + response_deserializer=metastore_federation.Federation.deserialize, + ) + return self._stubs['get_federation'] + + @property + def create_federation(self) -> Callable[ + [metastore_federation.CreateFederationRequest], + operations_pb2.Operation]: + r"""Return a callable for the create federation method over gRPC. + + Creates a metastore federation in a project and + location. + + Returns: + Callable[[~.CreateFederationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_federation' not in self._stubs: + self._stubs['create_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastoreFederation/CreateFederation', + request_serializer=metastore_federation.CreateFederationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_federation'] + + @property + def update_federation(self) -> Callable[ + [metastore_federation.UpdateFederationRequest], + operations_pb2.Operation]: + r"""Return a callable for the update federation method over gRPC. + + Updates the fields of a federation. + + Returns: + Callable[[~.UpdateFederationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_federation' not in self._stubs: + self._stubs['update_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastoreFederation/UpdateFederation', + request_serializer=metastore_federation.UpdateFederationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_federation'] + + @property + def delete_federation(self) -> Callable[ + [metastore_federation.DeleteFederationRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete federation method over gRPC. + + Deletes a single federation. + + Returns: + Callable[[~.DeleteFederationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_federation' not in self._stubs: + self._stubs['delete_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastoreFederation/DeleteFederation', + request_serializer=metastore_federation.DeleteFederationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_federation'] + + 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 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 set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'DataprocMetastoreFederationGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/grpc_asyncio.py new file mode 100644 index 0000000..bdcc4ba --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/grpc_asyncio.py @@ -0,0 +1,574 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1.types import metastore_federation +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from .base import DataprocMetastoreFederationTransport, DEFAULT_CLIENT_INFO +from .grpc import DataprocMetastoreFederationGrpcTransport + + +class DataprocMetastoreFederationGrpcAsyncIOTransport(DataprocMetastoreFederationTransport): + """gRPC AsyncIO backend transport for DataprocMetastoreFederation. + + Configures and manages metastore federation services. Dataproc + Metastore Federation Service allows federating a collection of + backend metastores like BigQuery, Dataplex Lakes, and other Dataproc + Metastores. The Federation Service exposes a gRPC URL through which + metadata from the backend metastores are served at query time. + + The Dataproc Metastore Federation API defines the following resource + model: + + - The service works with a collection of Google Cloud projects. + - Each project has a collection of available locations. + - Each location has a collection of federations. + - Dataproc Metastore Federations are resources with names of the + form: + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + 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 = 'metastore.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 = 'metastore.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] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + 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 operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_federations(self) -> Callable[ + [metastore_federation.ListFederationsRequest], + Awaitable[metastore_federation.ListFederationsResponse]]: + r"""Return a callable for the list federations method over gRPC. + + Lists federations in a project and location. + + Returns: + Callable[[~.ListFederationsRequest], + Awaitable[~.ListFederationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_federations' not in self._stubs: + self._stubs['list_federations'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastoreFederation/ListFederations', + request_serializer=metastore_federation.ListFederationsRequest.serialize, + response_deserializer=metastore_federation.ListFederationsResponse.deserialize, + ) + return self._stubs['list_federations'] + + @property + def get_federation(self) -> Callable[ + [metastore_federation.GetFederationRequest], + Awaitable[metastore_federation.Federation]]: + r"""Return a callable for the get federation method over gRPC. + + Gets the details of a single federation. + + Returns: + Callable[[~.GetFederationRequest], + Awaitable[~.Federation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_federation' not in self._stubs: + self._stubs['get_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastoreFederation/GetFederation', + request_serializer=metastore_federation.GetFederationRequest.serialize, + response_deserializer=metastore_federation.Federation.deserialize, + ) + return self._stubs['get_federation'] + + @property + def create_federation(self) -> Callable[ + [metastore_federation.CreateFederationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create federation method over gRPC. + + Creates a metastore federation in a project and + location. + + Returns: + Callable[[~.CreateFederationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_federation' not in self._stubs: + self._stubs['create_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastoreFederation/CreateFederation', + request_serializer=metastore_federation.CreateFederationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_federation'] + + @property + def update_federation(self) -> Callable[ + [metastore_federation.UpdateFederationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update federation method over gRPC. + + Updates the fields of a federation. + + Returns: + Callable[[~.UpdateFederationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_federation' not in self._stubs: + self._stubs['update_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastoreFederation/UpdateFederation', + request_serializer=metastore_federation.UpdateFederationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_federation'] + + @property + def delete_federation(self) -> Callable[ + [metastore_federation.DeleteFederationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete federation method over gRPC. + + Deletes a single federation. + + Returns: + Callable[[~.DeleteFederationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_federation' not in self._stubs: + self._stubs['delete_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1.DataprocMetastoreFederation/DeleteFederation', + request_serializer=metastore_federation.DeleteFederationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_federation'] + + 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 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 set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'DataprocMetastoreFederationGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/rest.py b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/rest.py new file mode 100644 index 0000000..21769f0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/rest.py @@ -0,0 +1,1519 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +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.metastore_v1.types import metastore_federation +from google.longrunning import operations_pb2 # type: ignore + +from .base import DataprocMetastoreFederationTransport, 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 DataprocMetastoreFederationRestInterceptor: + """Interceptor for DataprocMetastoreFederation. + + 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 DataprocMetastoreFederationRestTransport. + + .. code-block:: python + class MyCustomDataprocMetastoreFederationInterceptor(DataprocMetastoreFederationRestInterceptor): + def pre_create_federation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_federation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_federation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_federation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_federation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_federation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_federations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_federations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_federation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_federation(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DataprocMetastoreFederationRestTransport(interceptor=MyCustomDataprocMetastoreFederationInterceptor()) + client = DataprocMetastoreFederationClient(transport=transport) + + + """ + def pre_create_federation(self, request: metastore_federation.CreateFederationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore_federation.CreateFederationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_federation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_create_federation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_federation + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_delete_federation(self, request: metastore_federation.DeleteFederationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore_federation.DeleteFederationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_federation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_delete_federation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_federation + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_get_federation(self, request: metastore_federation.GetFederationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore_federation.GetFederationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_federation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_get_federation(self, response: metastore_federation.Federation) -> metastore_federation.Federation: + """Post-rpc interceptor for get_federation + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_list_federations(self, request: metastore_federation.ListFederationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore_federation.ListFederationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_federations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_list_federations(self, response: metastore_federation.ListFederationsResponse) -> metastore_federation.ListFederationsResponse: + """Post-rpc interceptor for list_federations + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_update_federation(self, request: metastore_federation.UpdateFederationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore_federation.UpdateFederationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_federation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_update_federation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_federation + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DataprocMetastoreFederationRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DataprocMetastoreFederationRestInterceptor + + +class DataprocMetastoreFederationRestTransport(DataprocMetastoreFederationTransport): + """REST backend transport for DataprocMetastoreFederation. + + Configures and manages metastore federation services. Dataproc + Metastore Federation Service allows federating a collection of + backend metastores like BigQuery, Dataplex Lakes, and other Dataproc + Metastores. The Federation Service exposes a gRPC URL through which + metadata from the backend metastores are served at query time. + + The Dataproc Metastore Federation API defines the following resource + model: + + - The service works with a collection of Google Cloud projects. + - Each project has a collection of available locations. + - Each location has a collection of federations. + - Dataproc Metastore Federations are resources with names of the + form: + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + 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 = 'metastore.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[DataprocMetastoreFederationRestInterceptor] = 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) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DataprocMetastoreFederationRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateFederation(DataprocMetastoreFederationRestStub): + def __hash__(self): + return hash("CreateFederation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "federationId" : "", } + + @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: metastore_federation.CreateFederationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create federation method over HTTP. + + Args: + request (~.metastore_federation.CreateFederationRequest): + The request object. Request message for CreateFederation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/federations', + 'body': 'federation', + }, + ] + request, metadata = self._interceptor.pre_create_federation(request, metadata) + pb_request = metastore_federation.CreateFederationRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_federation(resp) + return resp + + class _DeleteFederation(DataprocMetastoreFederationRestStub): + def __hash__(self): + return hash("DeleteFederation") + + __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: metastore_federation.DeleteFederationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete federation method over HTTP. + + Args: + request (~.metastore_federation.DeleteFederationRequest): + The request object. Request message for DeleteFederation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/federations/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_federation(request, metadata) + pb_request = metastore_federation.DeleteFederationRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_federation(resp) + return resp + + class _GetFederation(DataprocMetastoreFederationRestStub): + def __hash__(self): + return hash("GetFederation") + + __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: metastore_federation.GetFederationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore_federation.Federation: + r"""Call the get federation method over HTTP. + + Args: + request (~.metastore_federation.GetFederationRequest): + The request object. Request message for GetFederation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore_federation.Federation: + Represents a federation of multiple + backend metastores. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/federations/*}', + }, + ] + request, metadata = self._interceptor.pre_get_federation(request, metadata) + pb_request = metastore_federation.GetFederationRequest.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 = metastore_federation.Federation() + pb_resp = metastore_federation.Federation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_federation(resp) + return resp + + class _ListFederations(DataprocMetastoreFederationRestStub): + def __hash__(self): + return hash("ListFederations") + + __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: metastore_federation.ListFederationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore_federation.ListFederationsResponse: + r"""Call the list federations method over HTTP. + + Args: + request (~.metastore_federation.ListFederationsRequest): + The request object. Request message for ListFederations. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore_federation.ListFederationsResponse: + Response message for ListFederations + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/federations', + }, + ] + request, metadata = self._interceptor.pre_list_federations(request, metadata) + pb_request = metastore_federation.ListFederationsRequest.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 = metastore_federation.ListFederationsResponse() + pb_resp = metastore_federation.ListFederationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_federations(resp) + return resp + + class _UpdateFederation(DataprocMetastoreFederationRestStub): + def __hash__(self): + return hash("UpdateFederation") + + __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: metastore_federation.UpdateFederationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update federation method over HTTP. + + Args: + request (~.metastore_federation.UpdateFederationRequest): + The request object. Request message for UpdateFederation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{federation.name=projects/*/locations/*/federations/*}', + 'body': 'federation', + }, + ] + request, metadata = self._interceptor.pre_update_federation(request, metadata) + pb_request = metastore_federation.UpdateFederationRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_federation(resp) + return resp + + @property + def create_federation(self) -> Callable[ + [metastore_federation.CreateFederationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateFederation(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_federation(self) -> Callable[ + [metastore_federation.DeleteFederationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteFederation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_federation(self) -> Callable[ + [metastore_federation.GetFederationRequest], + metastore_federation.Federation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetFederation(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_federations(self) -> Callable[ + [metastore_federation.ListFederationsRequest], + metastore_federation.ListFederationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListFederations(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_federation(self) -> Callable[ + [metastore_federation.UpdateFederationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateFederation(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(DataprocMetastoreFederationRestStub): + 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(DataprocMetastoreFederationRestStub): + 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 get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(DataprocMetastoreFederationRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy 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: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/services/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/services/*/backups/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/federations/*}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(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 = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(DataprocMetastoreFederationRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy 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: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/services/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/services/*/backups/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/federations/*}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.loads(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) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(DataprocMetastoreFederationRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions 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: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/services/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/federations/*}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.loads(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) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(DataprocMetastoreFederationRestStub): + 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(DataprocMetastoreFederationRestStub): + 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(DataprocMetastoreFederationRestStub): + 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__=( + 'DataprocMetastoreFederationRestTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/metastore_v1/types/__init__.py new file mode 100644 index 0000000..b91473f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/types/__init__.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .metastore import ( + Backup, + CreateBackupRequest, + CreateMetadataImportRequest, + CreateServiceRequest, + DatabaseDumpSpec, + DeleteBackupRequest, + DeleteServiceRequest, + EncryptionConfig, + ExportMetadataRequest, + GetBackupRequest, + GetMetadataImportRequest, + GetServiceRequest, + HiveMetastoreConfig, + KerberosConfig, + ListBackupsRequest, + ListBackupsResponse, + ListMetadataImportsRequest, + ListMetadataImportsResponse, + ListServicesRequest, + ListServicesResponse, + LocationMetadata, + MaintenanceWindow, + MetadataExport, + MetadataImport, + MetadataManagementActivity, + NetworkConfig, + OperationMetadata, + Restore, + RestoreServiceRequest, + Secret, + Service, + TelemetryConfig, + UpdateMetadataImportRequest, + UpdateServiceRequest, +) +from .metastore_federation import ( + BackendMetastore, + CreateFederationRequest, + DeleteFederationRequest, + Federation, + GetFederationRequest, + ListFederationsRequest, + ListFederationsResponse, + UpdateFederationRequest, +) + +__all__ = ( + 'Backup', + 'CreateBackupRequest', + 'CreateMetadataImportRequest', + 'CreateServiceRequest', + 'DatabaseDumpSpec', + 'DeleteBackupRequest', + 'DeleteServiceRequest', + 'EncryptionConfig', + 'ExportMetadataRequest', + 'GetBackupRequest', + 'GetMetadataImportRequest', + 'GetServiceRequest', + 'HiveMetastoreConfig', + 'KerberosConfig', + 'ListBackupsRequest', + 'ListBackupsResponse', + 'ListMetadataImportsRequest', + 'ListMetadataImportsResponse', + 'ListServicesRequest', + 'ListServicesResponse', + 'LocationMetadata', + 'MaintenanceWindow', + 'MetadataExport', + 'MetadataImport', + 'MetadataManagementActivity', + 'NetworkConfig', + 'OperationMetadata', + 'Restore', + 'RestoreServiceRequest', + 'Secret', + 'Service', + 'TelemetryConfig', + 'UpdateMetadataImportRequest', + 'UpdateServiceRequest', + 'BackendMetastore', + 'CreateFederationRequest', + 'DeleteFederationRequest', + 'Federation', + 'GetFederationRequest', + 'ListFederationsRequest', + 'ListFederationsResponse', + 'UpdateFederationRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/types/metastore.py b/owl-bot-staging/v1/google/cloud/metastore_v1/types/metastore.py new file mode 100644 index 0000000..843881e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/types/metastore.py @@ -0,0 +1,1894 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __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.protobuf import wrappers_pb2 # type: ignore +from google.type import dayofweek_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.metastore.v1', + manifest={ + 'Service', + 'MaintenanceWindow', + 'HiveMetastoreConfig', + 'KerberosConfig', + 'Secret', + 'EncryptionConfig', + 'NetworkConfig', + 'TelemetryConfig', + 'MetadataManagementActivity', + 'MetadataImport', + 'MetadataExport', + 'Backup', + 'Restore', + 'ListServicesRequest', + 'ListServicesResponse', + 'GetServiceRequest', + 'CreateServiceRequest', + 'UpdateServiceRequest', + 'DeleteServiceRequest', + 'ListMetadataImportsRequest', + 'ListMetadataImportsResponse', + 'GetMetadataImportRequest', + 'CreateMetadataImportRequest', + 'UpdateMetadataImportRequest', + 'ListBackupsRequest', + 'ListBackupsResponse', + 'GetBackupRequest', + 'CreateBackupRequest', + 'DeleteBackupRequest', + 'ExportMetadataRequest', + 'RestoreServiceRequest', + 'OperationMetadata', + 'LocationMetadata', + 'DatabaseDumpSpec', + }, +) + + +class Service(proto.Message): + r"""A managed metastore service that serves metadata queries. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + hive_metastore_config (google.cloud.metastore_v1.types.HiveMetastoreConfig): + Configuration information specific to running + Hive metastore software as the metastore + service. + + This field is a member of `oneof`_ ``metastore_config``. + name (str): + Immutable. The relative resource name of the metastore + service, in the following format: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metastore + service was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metastore + service was last updated. + labels (MutableMapping[str, str]): + User-defined labels for the metastore + service. + network (str): + Immutable. The relative resource name of the VPC network on + which the instance can be accessed. It is specified in the + following form: + + ``projects/{project_number}/global/networks/{network_id}``. + endpoint_uri (str): + Output only. The URI of the endpoint used to + access the metastore service. + port (int): + The TCP port at which the metastore service + is reached. Default: 9083. + state (google.cloud.metastore_v1.types.Service.State): + Output only. The current state of the + metastore service. + state_message (str): + Output only. Additional information about the + current state of the metastore service, if + available. + artifact_gcs_uri (str): + Output only. A Cloud Storage URI (starting with ``gs://``) + that specifies where artifacts related to the metastore + service are stored. + tier (google.cloud.metastore_v1.types.Service.Tier): + The tier of the service. + maintenance_window (google.cloud.metastore_v1.types.MaintenanceWindow): + The one hour maintenance window of the + metastore service. This specifies when the + service can be restarted for maintenance + purposes in UTC time. Maintenance window is not + needed for services with the SPANNER database + type. + uid (str): + Output only. The globally unique resource + identifier of the metastore service. + metadata_management_activity (google.cloud.metastore_v1.types.MetadataManagementActivity): + Output only. The metadata management + activities of the metastore service. + release_channel (google.cloud.metastore_v1.types.Service.ReleaseChannel): + Immutable. The release channel of the service. If + unspecified, defaults to ``STABLE``. + encryption_config (google.cloud.metastore_v1.types.EncryptionConfig): + Immutable. Information used to configure the + Dataproc Metastore service to encrypt customer + data at rest. Cannot be updated. + network_config (google.cloud.metastore_v1.types.NetworkConfig): + The configuration specifying the network + settings for the Dataproc Metastore service. + database_type (google.cloud.metastore_v1.types.Service.DatabaseType): + Immutable. The database type that the + Metastore service stores its data. + telemetry_config (google.cloud.metastore_v1.types.TelemetryConfig): + The configuration specifying telemetry settings for the + Dataproc Metastore service. If unspecified defaults to + ``JSON``. + """ + class State(proto.Enum): + r"""The current state of the metastore service. + + Values: + STATE_UNSPECIFIED (0): + The state of the metastore service is + unknown. + CREATING (1): + The metastore service is in the process of + being created. + ACTIVE (2): + The metastore service is running and ready to + serve queries. + SUSPENDING (3): + The metastore service is entering suspension. + Its query-serving availability may cease + unexpectedly. + SUSPENDED (4): + The metastore service is suspended and unable + to serve queries. + UPDATING (5): + The metastore service is being updated. It + remains usable but cannot accept additional + update requests or be deleted at this time. + DELETING (6): + The metastore service is undergoing deletion. + It cannot be used. + ERROR (7): + The metastore service has encountered an + error and cannot be used. The metastore service + should be deleted. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + SUSPENDING = 3 + SUSPENDED = 4 + UPDATING = 5 + DELETING = 6 + ERROR = 7 + + class Tier(proto.Enum): + r"""Available service tiers. + + Values: + TIER_UNSPECIFIED (0): + The tier is not set. + DEVELOPER (1): + The developer tier provides limited + scalability and no fault tolerance. Good for + low-cost proof-of-concept. + ENTERPRISE (3): + The enterprise tier provides multi-zone high + availability, and sufficient scalability for + enterprise-level Dataproc Metastore workloads. + """ + TIER_UNSPECIFIED = 0 + DEVELOPER = 1 + ENTERPRISE = 3 + + class ReleaseChannel(proto.Enum): + r"""Release channels bundle features of varying levels of + stability. Newer features may be introduced initially into less + stable release channels and can be automatically promoted into + more stable release channels. + + Values: + RELEASE_CHANNEL_UNSPECIFIED (0): + Release channel is not specified. + CANARY (1): + The ``CANARY`` release channel contains the newest features, + which may be unstable and subject to unresolved issues with + no known workarounds. Services using the ``CANARY`` release + channel are not subject to any SLAs. + STABLE (2): + The ``STABLE`` release channel contains features that are + considered stable and have been validated for production + use. + """ + RELEASE_CHANNEL_UNSPECIFIED = 0 + CANARY = 1 + STABLE = 2 + + class DatabaseType(proto.Enum): + r"""The backend database type for the metastore service. + + Values: + DATABASE_TYPE_UNSPECIFIED (0): + The DATABASE_TYPE is not set. + MYSQL (1): + MySQL is used to persist the metastore data. + SPANNER (2): + Spanner is used to persist the metastore + data. + """ + DATABASE_TYPE_UNSPECIFIED = 0 + MYSQL = 1 + SPANNER = 2 + + hive_metastore_config: 'HiveMetastoreConfig' = proto.Field( + proto.MESSAGE, + number=5, + oneof='metastore_config', + message='HiveMetastoreConfig', + ) + 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, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + network: str = proto.Field( + proto.STRING, + number=7, + ) + endpoint_uri: str = proto.Field( + proto.STRING, + number=8, + ) + port: int = proto.Field( + proto.INT32, + number=9, + ) + state: State = proto.Field( + proto.ENUM, + number=10, + enum=State, + ) + state_message: str = proto.Field( + proto.STRING, + number=11, + ) + artifact_gcs_uri: str = proto.Field( + proto.STRING, + number=12, + ) + tier: Tier = proto.Field( + proto.ENUM, + number=13, + enum=Tier, + ) + maintenance_window: 'MaintenanceWindow' = proto.Field( + proto.MESSAGE, + number=15, + message='MaintenanceWindow', + ) + uid: str = proto.Field( + proto.STRING, + number=16, + ) + metadata_management_activity: 'MetadataManagementActivity' = proto.Field( + proto.MESSAGE, + number=17, + message='MetadataManagementActivity', + ) + release_channel: ReleaseChannel = proto.Field( + proto.ENUM, + number=19, + enum=ReleaseChannel, + ) + encryption_config: 'EncryptionConfig' = proto.Field( + proto.MESSAGE, + number=20, + message='EncryptionConfig', + ) + network_config: 'NetworkConfig' = proto.Field( + proto.MESSAGE, + number=21, + message='NetworkConfig', + ) + database_type: DatabaseType = proto.Field( + proto.ENUM, + number=22, + enum=DatabaseType, + ) + telemetry_config: 'TelemetryConfig' = proto.Field( + proto.MESSAGE, + number=23, + message='TelemetryConfig', + ) + + +class MaintenanceWindow(proto.Message): + r"""Maintenance window. This specifies when Dataproc Metastore + may perform system maintenance operation to the service. + + Attributes: + hour_of_day (google.protobuf.wrappers_pb2.Int32Value): + The hour of day (0-23) when the window + starts. + day_of_week (google.type.dayofweek_pb2.DayOfWeek): + The day of week, when the window starts. + """ + + hour_of_day: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=1, + message=wrappers_pb2.Int32Value, + ) + day_of_week: dayofweek_pb2.DayOfWeek = proto.Field( + proto.ENUM, + number=2, + enum=dayofweek_pb2.DayOfWeek, + ) + + +class HiveMetastoreConfig(proto.Message): + r"""Specifies configuration information specific to running Hive + metastore software as the metastore service. + + Attributes: + version (str): + Immutable. The Hive metastore schema version. + config_overrides (MutableMapping[str, str]): + A mapping of Hive metastore configuration key-value pairs to + apply to the Hive metastore (configured in + ``hive-site.xml``). The mappings override system defaults + (some keys cannot be overridden). These overrides are also + applied to auxiliary versions and can be further customized + in the auxiliary version's ``AuxiliaryVersionConfig``. + kerberos_config (google.cloud.metastore_v1.types.KerberosConfig): + Information used to configure the Hive metastore service as + a service principal in a Kerberos realm. To disable + Kerberos, use the ``UpdateService`` method and specify this + field's path (``hive_metastore_config.kerberos_config``) in + the request's ``update_mask`` while omitting this field from + the request's ``service``. + """ + + version: str = proto.Field( + proto.STRING, + number=1, + ) + config_overrides: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + kerberos_config: 'KerberosConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='KerberosConfig', + ) + + +class KerberosConfig(proto.Message): + r"""Configuration information for a Kerberos principal. + + Attributes: + keytab (google.cloud.metastore_v1.types.Secret): + A Kerberos keytab file that can be used to + authenticate a service principal with a Kerberos + Key Distribution Center (KDC). + principal (str): + A Kerberos principal that exists in the both the keytab the + KDC to authenticate as. A typical principal is of the form + ``primary/instance@REALM``, but there is no exact format. + krb5_config_gcs_uri (str): + A Cloud Storage URI that specifies the path to a krb5.conf + file. It is of the form + ``gs://{bucket_name}/path/to/krb5.conf``, although the file + does not need to be named krb5.conf explicitly. + """ + + keytab: 'Secret' = proto.Field( + proto.MESSAGE, + number=1, + message='Secret', + ) + principal: str = proto.Field( + proto.STRING, + number=2, + ) + krb5_config_gcs_uri: str = proto.Field( + proto.STRING, + number=3, + ) + + +class Secret(proto.Message): + r"""A securely stored value. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_secret (str): + The relative resource name of a Secret Manager secret + version, in the following form: + + ``projects/{project_number}/secrets/{secret_id}/versions/{version_id}``. + + This field is a member of `oneof`_ ``value``. + """ + + cloud_secret: str = proto.Field( + proto.STRING, + number=2, + oneof='value', + ) + + +class EncryptionConfig(proto.Message): + r"""Encryption settings for the service. + + Attributes: + kms_key (str): + The fully qualified customer provided Cloud KMS key name to + use for customer data encryption, in the following form: + + ``projects/{project_number}/locations/{location_id}/keyRings/{key_ring_id}/cryptoKeys/{crypto_key_id}``. + """ + + kms_key: str = proto.Field( + proto.STRING, + number=1, + ) + + +class NetworkConfig(proto.Message): + r"""Network configuration for the Dataproc Metastore service. + + Attributes: + consumers (MutableSequence[google.cloud.metastore_v1.types.NetworkConfig.Consumer]): + Immutable. The consumer-side network + configuration for the Dataproc Metastore + instance. + """ + + class Consumer(proto.Message): + r"""Contains information of the customer's network + configurations. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + subnetwork (str): + Immutable. The subnetwork of the customer project from which + an IP address is reserved and used as the Dataproc Metastore + service's endpoint. It is accessible to hosts in the subnet + and to all hosts in a subnet in the same region and same + network. There must be at least one IP address available in + the subnet's primary range. The subnet is specified in the + following form: + + ``projects/{project_number}/regions/{region_id}/subnetworks/{subnetwork_id}`` + + This field is a member of `oneof`_ ``vpc_resource``. + endpoint_uri (str): + Output only. The URI of the endpoint used to + access the metastore service. + """ + + subnetwork: str = proto.Field( + proto.STRING, + number=1, + oneof='vpc_resource', + ) + endpoint_uri: str = proto.Field( + proto.STRING, + number=3, + ) + + consumers: MutableSequence[Consumer] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Consumer, + ) + + +class TelemetryConfig(proto.Message): + r"""Telemetry Configuration for the Dataproc Metastore service. + + Attributes: + log_format (google.cloud.metastore_v1.types.TelemetryConfig.LogFormat): + The output format of the Dataproc Metastore + service's logs. + """ + class LogFormat(proto.Enum): + r""" + + Values: + LOG_FORMAT_UNSPECIFIED (0): + The LOG_FORMAT is not set. + LEGACY (1): + Logging output uses the legacy ``textPayload`` format. + JSON (2): + Logging output uses the ``jsonPayload`` format. + """ + LOG_FORMAT_UNSPECIFIED = 0 + LEGACY = 1 + JSON = 2 + + log_format: LogFormat = proto.Field( + proto.ENUM, + number=1, + enum=LogFormat, + ) + + +class MetadataManagementActivity(proto.Message): + r"""The metadata management activities of the metastore service. + + Attributes: + metadata_exports (MutableSequence[google.cloud.metastore_v1.types.MetadataExport]): + Output only. The latest metadata exports of + the metastore service. + restores (MutableSequence[google.cloud.metastore_v1.types.Restore]): + Output only. The latest restores of the + metastore service. + """ + + metadata_exports: MutableSequence['MetadataExport'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='MetadataExport', + ) + restores: MutableSequence['Restore'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Restore', + ) + + +class MetadataImport(proto.Message): + r"""A metastore resource that imports metadata. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + database_dump (google.cloud.metastore_v1.types.MetadataImport.DatabaseDump): + Immutable. A database dump from a + pre-existing metastore's database. + + This field is a member of `oneof`_ ``metadata``. + name (str): + Immutable. The relative resource name of the metadata + import, of the form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports/{metadata_import_id}``. + description (str): + The description of the metadata import. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metadata + import was started. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metadata + import was last updated. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metadata + import finished. + state (google.cloud.metastore_v1.types.MetadataImport.State): + Output only. The current state of the + metadata import. + """ + class State(proto.Enum): + r"""The current state of the metadata import. + + Values: + STATE_UNSPECIFIED (0): + The state of the metadata import is unknown. + RUNNING (1): + The metadata import is running. + SUCCEEDED (2): + The metadata import completed successfully. + UPDATING (3): + The metadata import is being updated. + FAILED (4): + The metadata import failed, and attempted + metadata changes were rolled back. + """ + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + UPDATING = 3 + FAILED = 4 + + class DatabaseDump(proto.Message): + r"""A specification of the location of and metadata about a + database dump from a relational database management system. + + Attributes: + database_type (google.cloud.metastore_v1.types.MetadataImport.DatabaseDump.DatabaseType): + The type of the database. + gcs_uri (str): + A Cloud Storage object or folder URI that specifies the + source from which to import metadata. It must begin with + ``gs://``. + type_ (google.cloud.metastore_v1.types.DatabaseDumpSpec.Type): + Optional. The type of the database dump. If unspecified, + defaults to ``MYSQL``. + """ + class DatabaseType(proto.Enum): + r"""The type of the database. + + Values: + DATABASE_TYPE_UNSPECIFIED (0): + The type of the source database is unknown. + MYSQL (1): + The type of the source database is MySQL. + """ + DATABASE_TYPE_UNSPECIFIED = 0 + MYSQL = 1 + + database_type: 'MetadataImport.DatabaseDump.DatabaseType' = proto.Field( + proto.ENUM, + number=1, + enum='MetadataImport.DatabaseDump.DatabaseType', + ) + gcs_uri: str = proto.Field( + proto.STRING, + number=2, + ) + type_: 'DatabaseDumpSpec.Type' = proto.Field( + proto.ENUM, + number=4, + enum='DatabaseDumpSpec.Type', + ) + + database_dump: DatabaseDump = proto.Field( + proto.MESSAGE, + number=6, + oneof='metadata', + message=DatabaseDump, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + state: State = proto.Field( + proto.ENUM, + number=5, + enum=State, + ) + + +class MetadataExport(proto.Message): + r"""The details of a metadata export operation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + destination_gcs_uri (str): + Output only. A Cloud Storage URI of a folder that metadata + are exported to, in the form of + ``gs:////``, + where ```` is automatically generated. + + This field is a member of `oneof`_ ``destination``. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the export + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the export ended. + state (google.cloud.metastore_v1.types.MetadataExport.State): + Output only. The current state of the export. + database_dump_type (google.cloud.metastore_v1.types.DatabaseDumpSpec.Type): + Output only. The type of the database dump. + """ + class State(proto.Enum): + r"""The current state of the metadata export. + + Values: + STATE_UNSPECIFIED (0): + The state of the metadata export is unknown. + RUNNING (1): + The metadata export is running. + SUCCEEDED (2): + The metadata export completed successfully. + FAILED (3): + The metadata export failed. + CANCELLED (4): + The metadata export is cancelled. + """ + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + FAILED = 3 + CANCELLED = 4 + + destination_gcs_uri: str = proto.Field( + proto.STRING, + number=4, + oneof='destination', + ) + start_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, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + database_dump_type: 'DatabaseDumpSpec.Type' = proto.Field( + proto.ENUM, + number=5, + enum='DatabaseDumpSpec.Type', + ) + + +class Backup(proto.Message): + r"""The details of a backup resource. + + Attributes: + name (str): + Immutable. The relative resource name of the backup, in the + following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the backup was + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the backup + finished creating. + state (google.cloud.metastore_v1.types.Backup.State): + Output only. The current state of the backup. + service_revision (google.cloud.metastore_v1.types.Service): + Output only. The revision of the service at + the time of backup. + description (str): + The description of the backup. + restoring_services (MutableSequence[str]): + Output only. Services that are restoring from + the backup. + """ + class State(proto.Enum): + r"""The current state of the backup. + + Values: + STATE_UNSPECIFIED (0): + The state of the backup is unknown. + CREATING (1): + The backup is being created. + DELETING (2): + The backup is being deleted. + ACTIVE (3): + The backup is active and ready to use. + FAILED (4): + The backup failed. + RESTORING (5): + The backup is being restored. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + DELETING = 2 + ACTIVE = 3 + FAILED = 4 + RESTORING = 5 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + service_revision: 'Service' = proto.Field( + proto.MESSAGE, + number=5, + message='Service', + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + restoring_services: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + +class Restore(proto.Message): + r"""The details of a metadata restore operation. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the restore + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the restore ended. + state (google.cloud.metastore_v1.types.Restore.State): + Output only. The current state of the + restore. + backup (str): + Output only. The relative resource name of the metastore + service backup to restore from, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + type_ (google.cloud.metastore_v1.types.Restore.RestoreType): + Output only. The type of restore. + details (str): + Output only. The restore details containing + the revision of the service to be restored to, + in format of JSON. + """ + class State(proto.Enum): + r"""The current state of the restore. + + Values: + STATE_UNSPECIFIED (0): + The state of the metadata restore is unknown. + RUNNING (1): + The metadata restore is running. + SUCCEEDED (2): + The metadata restore completed successfully. + FAILED (3): + The metadata restore failed. + CANCELLED (4): + The metadata restore is cancelled. + """ + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + FAILED = 3 + CANCELLED = 4 + + class RestoreType(proto.Enum): + r"""The type of restore. If unspecified, defaults to ``METADATA_ONLY``. + + Values: + RESTORE_TYPE_UNSPECIFIED (0): + The restore type is unknown. + FULL (1): + The service's metadata and configuration are + restored. + METADATA_ONLY (2): + Only the service's metadata is restored. + """ + RESTORE_TYPE_UNSPECIFIED = 0 + FULL = 1 + METADATA_ONLY = 2 + + start_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, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + backup: str = proto.Field( + proto.STRING, + number=4, + ) + type_: RestoreType = proto.Field( + proto.ENUM, + number=5, + enum=RestoreType, + ) + details: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ListServicesRequest(proto.Message): + r"""Request message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1.DataprocMetastore.ListServices]. + + Attributes: + parent (str): + Required. The relative resource name of the location of + metastore services to list, in the following form: + + ``projects/{project_number}/locations/{location_id}``. + page_size (int): + Optional. The maximum number of services to + return. The response may contain less than the + maximum number. If unspecified, no more than 500 + services are returned. The maximum value is + 1000; values above 1000 are changed to 1000. + page_token (str): + Optional. A page token, received from a previous + [DataprocMetastore.ListServices][google.cloud.metastore.v1.DataprocMetastore.ListServices] + call. Provide this token to retrieve the subsequent page. + + To retrieve the first page, supply an empty page token. + + When paginating, other parameters provided to + [DataprocMetastore.ListServices][google.cloud.metastore.v1.DataprocMetastore.ListServices] + must match the call that provided the page token. + filter (str): + Optional. The filter to apply to list + results. + order_by (str): + Optional. Specify the ordering of results as described in + `Sorting + Order `__. + If not specified, the results will be sorted in the default + order. + """ + + 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 ListServicesResponse(proto.Message): + r"""Response message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1.DataprocMetastore.ListServices]. + + Attributes: + services (MutableSequence[google.cloud.metastore_v1.types.Service]): + The services in the specified location. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + services: MutableSequence['Service'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Service', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetServiceRequest(proto.Message): + r"""Request message for + [DataprocMetastore.GetService][google.cloud.metastore.v1.DataprocMetastore.GetService]. + + Attributes: + name (str): + Required. The relative resource name of the metastore + service to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateServiceRequest(proto.Message): + r"""Request message for + [DataprocMetastore.CreateService][google.cloud.metastore.v1.DataprocMetastore.CreateService]. + + Attributes: + parent (str): + Required. The relative resource name of the location in + which to create a metastore service, in the following form: + + ``projects/{project_number}/locations/{location_id}``. + service_id (str): + Required. The ID of the metastore service, + which is used as the final component of the + metastore service's name. + This value must be between 2 and 63 characters + long inclusive, begin with a letter, end with a + letter or number, and consist of alpha-numeric + ASCII characters or hyphens. + service (google.cloud.metastore_v1.types.Service): + Required. The Metastore service to create. The ``name`` + field is ignored. The ID of the created metastore service + must be provided in the request's ``service_id`` field. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + service_id: str = proto.Field( + proto.STRING, + number=2, + ) + service: 'Service' = proto.Field( + proto.MESSAGE, + number=3, + message='Service', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateServiceRequest(proto.Message): + r"""Request message for + [DataprocMetastore.UpdateService][google.cloud.metastore.v1.DataprocMetastore.UpdateService]. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask used to specify the fields to be + overwritten in the metastore service resource by the update. + Fields specified in the ``update_mask`` are relative to the + resource (not to the full request). A field is overwritten + if it is in the mask. + service (google.cloud.metastore_v1.types.Service): + Required. The metastore service to update. The server only + merges fields in the service if they are specified in + ``update_mask``. + + The metastore service's ``name`` field is used to identify + the metastore service to be updated. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + service: 'Service' = proto.Field( + proto.MESSAGE, + number=2, + message='Service', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteServiceRequest(proto.Message): + r"""Request message for + [DataprocMetastore.DeleteService][google.cloud.metastore.v1.DataprocMetastore.DeleteService]. + + Attributes: + name (str): + Required. The relative resource name of the metastore + service to delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListMetadataImportsRequest(proto.Message): + r"""Request message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1.DataprocMetastore.ListMetadataImports]. + + Attributes: + parent (str): + Required. The relative resource name of the service whose + metadata imports to list, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports``. + page_size (int): + Optional. The maximum number of imports to + return. The response may contain less than the + maximum number. If unspecified, no more than 500 + imports are returned. The maximum value is 1000; + values above 1000 are changed to 1000. + page_token (str): + Optional. A page token, received from a previous + [DataprocMetastore.ListServices][google.cloud.metastore.v1.DataprocMetastore.ListServices] + call. Provide this token to retrieve the subsequent page. + + To retrieve the first page, supply an empty page token. + + When paginating, other parameters provided to + [DataprocMetastore.ListServices][google.cloud.metastore.v1.DataprocMetastore.ListServices] + must match the call that provided the page token. + filter (str): + Optional. The filter to apply to list + results. + order_by (str): + Optional. Specify the ordering of results as described in + `Sorting + Order `__. + If not specified, the results will be sorted in the default + order. + """ + + 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 ListMetadataImportsResponse(proto.Message): + r"""Response message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1.DataprocMetastore.ListMetadataImports]. + + Attributes: + metadata_imports (MutableSequence[google.cloud.metastore_v1.types.MetadataImport]): + The imports in the specified service. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + metadata_imports: MutableSequence['MetadataImport'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='MetadataImport', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetMetadataImportRequest(proto.Message): + r"""Request message for + [DataprocMetastore.GetMetadataImport][google.cloud.metastore.v1.DataprocMetastore.GetMetadataImport]. + + Attributes: + name (str): + Required. The relative resource name of the metadata import + to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports/{import_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateMetadataImportRequest(proto.Message): + r"""Request message for + [DataprocMetastore.CreateMetadataImport][google.cloud.metastore.v1.DataprocMetastore.CreateMetadataImport]. + + Attributes: + parent (str): + Required. The relative resource name of the service in which + to create a metastore import, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + metadata_import_id (str): + Required. The ID of the metadata import, + which is used as the final component of the + metadata import's name. + This value must be between 1 and 64 characters + long, begin with a letter, end with a letter or + number, and consist of alpha-numeric ASCII + characters or hyphens. + metadata_import (google.cloud.metastore_v1.types.MetadataImport): + Required. The metadata import to create. The ``name`` field + is ignored. The ID of the created metadata import must be + provided in the request's ``metadata_import_id`` field. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + metadata_import_id: str = proto.Field( + proto.STRING, + number=2, + ) + metadata_import: 'MetadataImport' = proto.Field( + proto.MESSAGE, + number=3, + message='MetadataImport', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateMetadataImportRequest(proto.Message): + r"""Request message for + [DataprocMetastore.UpdateMetadataImport][google.cloud.metastore.v1.DataprocMetastore.UpdateMetadataImport]. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask used to specify the fields to be + overwritten in the metadata import resource by the update. + Fields specified in the ``update_mask`` are relative to the + resource (not to the full request). A field is overwritten + if it is in the mask. + metadata_import (google.cloud.metastore_v1.types.MetadataImport): + Required. The metadata import to update. The server only + merges fields in the import if they are specified in + ``update_mask``. + + The metadata import's ``name`` field is used to identify the + metastore import to be updated. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + metadata_import: 'MetadataImport' = proto.Field( + proto.MESSAGE, + number=2, + message='MetadataImport', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListBackupsRequest(proto.Message): + r"""Request message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1.DataprocMetastore.ListBackups]. + + Attributes: + parent (str): + Required. The relative resource name of the service whose + backups to list, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups``. + page_size (int): + Optional. The maximum number of backups to + return. The response may contain less than the + maximum number. If unspecified, no more than 500 + backups are returned. The maximum value is 1000; + values above 1000 are changed to 1000. + page_token (str): + Optional. A page token, received from a previous + [DataprocMetastore.ListBackups][google.cloud.metastore.v1.DataprocMetastore.ListBackups] + call. Provide this token to retrieve the subsequent page. + + To retrieve the first page, supply an empty page token. + + When paginating, other parameters provided to + [DataprocMetastore.ListBackups][google.cloud.metastore.v1.DataprocMetastore.ListBackups] + must match the call that provided the page token. + filter (str): + Optional. The filter to apply to list + results. + order_by (str): + Optional. Specify the ordering of results as described in + `Sorting + Order `__. + If not specified, the results will be sorted in the default + order. + """ + + 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 ListBackupsResponse(proto.Message): + r"""Response message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1.DataprocMetastore.ListBackups]. + + Attributes: + backups (MutableSequence[google.cloud.metastore_v1.types.Backup]): + The backups of the specified service. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + backups: MutableSequence['Backup'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Backup', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetBackupRequest(proto.Message): + r"""Request message for + [DataprocMetastore.GetBackup][google.cloud.metastore.v1.DataprocMetastore.GetBackup]. + + Attributes: + name (str): + Required. The relative resource name of the backup to + retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateBackupRequest(proto.Message): + r"""Request message for + [DataprocMetastore.CreateBackup][google.cloud.metastore.v1.DataprocMetastore.CreateBackup]. + + Attributes: + parent (str): + Required. The relative resource name of the service in which + to create a backup of the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + backup_id (str): + Required. The ID of the backup, which is used + as the final component of the backup's name. + + This value must be between 1 and 64 characters + long, begin with a letter, end with a letter or + number, and consist of alpha-numeric ASCII + characters or hyphens. + backup (google.cloud.metastore_v1.types.Backup): + Required. The backup to create. The ``name`` field is + ignored. The ID of the created backup must be provided in + the request's ``backup_id`` field. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + backup_id: str = proto.Field( + proto.STRING, + number=2, + ) + backup: 'Backup' = proto.Field( + proto.MESSAGE, + number=3, + message='Backup', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class DeleteBackupRequest(proto.Message): + r"""Request message for + [DataprocMetastore.DeleteBackup][google.cloud.metastore.v1.DataprocMetastore.DeleteBackup]. + + Attributes: + name (str): + Required. The relative resource name of the backup to + delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ExportMetadataRequest(proto.Message): + r"""Request message for + [DataprocMetastore.ExportMetadata][google.cloud.metastore.v1.DataprocMetastore.ExportMetadata]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + destination_gcs_folder (str): + A Cloud Storage URI of a folder, in the format + ``gs:///``. A sub-folder + ```` containing exported files will be + created below it. + + This field is a member of `oneof`_ ``destination``. + service (str): + Required. The relative resource name of the metastore + service to run export, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}``. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__. + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + database_dump_type (google.cloud.metastore_v1.types.DatabaseDumpSpec.Type): + Optional. The type of the database dump. If unspecified, + defaults to ``MYSQL``. + """ + + destination_gcs_folder: str = proto.Field( + proto.STRING, + number=2, + oneof='destination', + ) + service: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + database_dump_type: 'DatabaseDumpSpec.Type' = proto.Field( + proto.ENUM, + number=4, + enum='DatabaseDumpSpec.Type', + ) + + +class RestoreServiceRequest(proto.Message): + r"""Request message for [DataprocMetastore.Restore][]. + + Attributes: + service (str): + Required. The relative resource name of the metastore + service to run restore, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}``. + backup (str): + Required. The relative resource name of the metastore + service backup to restore from, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + restore_type (google.cloud.metastore_v1.types.Restore.RestoreType): + Optional. The type of restore. If unspecified, defaults to + ``METADATA_ONLY``. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__. + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + service: str = proto.Field( + proto.STRING, + number=1, + ) + backup: str = proto.Field( + proto.STRING, + number=2, + ) + restore_type: 'Restore.RestoreType' = proto.Field( + proto.ENUM, + number=3, + enum='Restore.RestoreType', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of a 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 caller has requested + cancellation of the operation. Operations that have + successfully been cancelled 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 LocationMetadata(proto.Message): + r"""Metadata about the service in a location. + + Attributes: + supported_hive_metastore_versions (MutableSequence[google.cloud.metastore_v1.types.LocationMetadata.HiveMetastoreVersion]): + The versions of Hive Metastore that can be used when + creating a new metastore service in this location. The + server guarantees that exactly one ``HiveMetastoreVersion`` + in the list will set ``is_default``. + """ + + class HiveMetastoreVersion(proto.Message): + r"""A specification of a supported version of the Hive Metastore + software. + + Attributes: + version (str): + The semantic version of the Hive Metastore + software. + is_default (bool): + Whether ``version`` will be chosen by the server if a + metastore service is created with a ``HiveMetastoreConfig`` + that omits the ``version``. + """ + + version: str = proto.Field( + proto.STRING, + number=1, + ) + is_default: bool = proto.Field( + proto.BOOL, + number=2, + ) + + supported_hive_metastore_versions: MutableSequence[HiveMetastoreVersion] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=HiveMetastoreVersion, + ) + + +class DatabaseDumpSpec(proto.Message): + r"""The specification of database dump to import from or export + to. + + """ + class Type(proto.Enum): + r"""The type of the database dump. + + Values: + TYPE_UNSPECIFIED (0): + The type of the database dump is unknown. + MYSQL (1): + Database dump is a MySQL dump file. + AVRO (2): + Database dump contains Avro files. + """ + TYPE_UNSPECIFIED = 0 + MYSQL = 1 + AVRO = 2 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/metastore_v1/types/metastore_federation.py b/owl-bot-staging/v1/google/cloud/metastore_v1/types/metastore_federation.py new file mode 100644 index 0000000..1f1773e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/metastore_v1/types/metastore_federation.py @@ -0,0 +1,463 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.metastore.v1', + manifest={ + 'Federation', + 'BackendMetastore', + 'ListFederationsRequest', + 'ListFederationsResponse', + 'GetFederationRequest', + 'CreateFederationRequest', + 'UpdateFederationRequest', + 'DeleteFederationRequest', + }, +) + + +class Federation(proto.Message): + r"""Represents a federation of multiple backend metastores. + + Attributes: + name (str): + Immutable. The relative resource name of the federation, of + the form: + projects/{project_number}/locations/{location_id}/federations/{federation_id}`. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metastore + federation was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metastore + federation was last updated. + labels (MutableMapping[str, str]): + User-defined labels for the metastore + federation. + version (str): + Immutable. The Apache Hive metastore version + of the federation. All backend metastore + versions must be compatible with the federation + version. + backend_metastores (MutableMapping[int, google.cloud.metastore_v1.types.BackendMetastore]): + A map from ``BackendMetastore`` rank to + ``BackendMetastore``\ s from which the federation service + serves metadata at query time. The map key represents the + order in which ``BackendMetastore``\ s should be evaluated + to resolve database names at query time and should be + greater than or equal to zero. A ``BackendMetastore`` with a + lower number will be evaluated before a ``BackendMetastore`` + with a higher number. + endpoint_uri (str): + Output only. The federation endpoint. + state (google.cloud.metastore_v1.types.Federation.State): + Output only. The current state of the + federation. + state_message (str): + Output only. Additional information about the + current state of the metastore federation, if + available. + uid (str): + Output only. The globally unique resource + identifier of the metastore federation. + """ + class State(proto.Enum): + r"""The current state of the federation. + + Values: + STATE_UNSPECIFIED (0): + The state of the metastore federation is + unknown. + CREATING (1): + The metastore federation is in the process of + being created. + ACTIVE (2): + The metastore federation is running and ready + to serve queries. + UPDATING (3): + The metastore federation is being updated. It + remains usable but cannot accept additional + update requests or be deleted at this time. + DELETING (4): + The metastore federation is undergoing + deletion. It cannot be used. + ERROR (5): + The metastore federation has encountered an + error and cannot be used. The metastore + federation should be deleted. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + UPDATING = 3 + DELETING = 4 + ERROR = 5 + + 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, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + version: str = proto.Field( + proto.STRING, + number=5, + ) + backend_metastores: MutableMapping[int, 'BackendMetastore'] = proto.MapField( + proto.INT32, + proto.MESSAGE, + number=6, + message='BackendMetastore', + ) + endpoint_uri: str = proto.Field( + proto.STRING, + number=7, + ) + state: State = proto.Field( + proto.ENUM, + number=8, + enum=State, + ) + state_message: str = proto.Field( + proto.STRING, + number=9, + ) + uid: str = proto.Field( + proto.STRING, + number=10, + ) + + +class BackendMetastore(proto.Message): + r"""Represents a backend metastore for the federation. + + Attributes: + name (str): + The relative resource name of the metastore that is being + federated. The formats of the relative resource names for + the currently supported metastores are listed below: + + - Dataplex + + - ``projects/{project_id}/locations/{location}/lakes/{lake_id}`` + + - BigQuery + + - ``projects/{project_id}`` + + - Dataproc Metastore + + - ``projects/{project_id}/locations/{location}/services/{service_id}`` + metastore_type (google.cloud.metastore_v1.types.BackendMetastore.MetastoreType): + The type of the backend metastore. + """ + class MetastoreType(proto.Enum): + r"""The type of the backend metastore. + + Values: + METASTORE_TYPE_UNSPECIFIED (0): + The metastore type is not set. + DATAPROC_METASTORE (3): + The backend metastore is Dataproc Metastore. + """ + METASTORE_TYPE_UNSPECIFIED = 0 + DATAPROC_METASTORE = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + metastore_type: MetastoreType = proto.Field( + proto.ENUM, + number=2, + enum=MetastoreType, + ) + + +class ListFederationsRequest(proto.Message): + r"""Request message for ListFederations. + + Attributes: + parent (str): + Required. The relative resource name of the location of + metastore federations to list, in the following form: + ``projects/{project_number}/locations/{location_id}``. + page_size (int): + Optional. The maximum number of federations + to return. The response may contain less than + the maximum number. If unspecified, no more than + 500 services are returned. The maximum value is + 1000; values above 1000 are changed to 1000. + page_token (str): + Optional. A page token, received from a + previous ListFederationServices call. Provide + this token to retrieve the subsequent page. + To retrieve the first page, supply an empty page + token. + When paginating, other parameters provided to + ListFederationServices must match the call that + provided the page token. + filter (str): + Optional. The filter to apply to list + results. + order_by (str): + Optional. Specify the ordering of results as described in + `Sorting + Order `__. + If not specified, the results will be sorted in the default + order. + """ + + 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 ListFederationsResponse(proto.Message): + r"""Response message for ListFederations + + Attributes: + federations (MutableSequence[google.cloud.metastore_v1.types.Federation]): + The services in the specified location. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + federations: MutableSequence['Federation'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Federation', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetFederationRequest(proto.Message): + r"""Request message for GetFederation. + + Attributes: + name (str): + Required. The relative resource name of the metastore + federation to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateFederationRequest(proto.Message): + r"""Request message for CreateFederation. + + Attributes: + parent (str): + Required. The relative resource name of the location in + which to create a federation service, in the following form: + + ``projects/{project_number}/locations/{location_id}``. + federation_id (str): + Required. The ID of the metastore federation, + which is used as the final component of the + metastore federation's name. + This value must be between 2 and 63 characters + long inclusive, begin with a letter, end with a + letter or number, and consist of alpha-numeric + ASCII characters or hyphens. + federation (google.cloud.metastore_v1.types.Federation): + Required. The Metastore Federation to create. The ``name`` + field is ignored. The ID of the created metastore federation + must be provided in the request's ``federation_id`` field. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + federation_id: str = proto.Field( + proto.STRING, + number=2, + ) + federation: 'Federation' = proto.Field( + proto.MESSAGE, + number=3, + message='Federation', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateFederationRequest(proto.Message): + r"""Request message for UpdateFederation. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask used to specify the fields to be + overwritten in the metastore federation resource by the + update. Fields specified in the ``update_mask`` are relative + to the resource (not to the full request). A field is + overwritten if it is in the mask. + federation (google.cloud.metastore_v1.types.Federation): + Required. The metastore federation to update. The server + only merges fields in the service if they are specified in + ``update_mask``. + + The metastore federation's ``name`` field is used to + identify the metastore service to be updated. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + federation: 'Federation' = proto.Field( + proto.MESSAGE, + number=2, + message='Federation', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteFederationRequest(proto.Message): + r"""Request message for DeleteFederation. + + Attributes: + name (str): + Required. The relative resource name of the metastore + federation to delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 0000000..574c5ae --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 0000000..6ad4502 --- /dev/null +++ b/owl-bot-staging/v1/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "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/metastore_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/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_create_backup_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_create_backup_async.py new file mode 100644 index 0000000..69442fe --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_create_backup_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateBackup +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_CreateBackup_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 metastore_v1 + + +async def sample_create_backup(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + ) + + # Make the request + operation = client.create_backup(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_CreateBackup_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_create_backup_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_create_backup_sync.py new file mode 100644 index 0000000..4413ea7 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_create_backup_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateBackup +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_CreateBackup_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 metastore_v1 + + +def sample_create_backup(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + ) + + # Make the request + operation = client.create_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_CreateBackup_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_create_metadata_import_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_create_metadata_import_async.py new file mode 100644 index 0000000..e7b3dc8 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_create_metadata_import_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMetadataImport +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_CreateMetadataImport_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 metastore_v1 + + +async def sample_create_metadata_import(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.CreateMetadataImportRequest( + parent="parent_value", + metadata_import_id="metadata_import_id_value", + ) + + # Make the request + operation = client.create_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_CreateMetadataImport_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_create_metadata_import_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_create_metadata_import_sync.py new file mode 100644 index 0000000..4ebc7ff --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_create_metadata_import_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMetadataImport +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_CreateMetadataImport_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 metastore_v1 + + +def sample_create_metadata_import(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.CreateMetadataImportRequest( + parent="parent_value", + metadata_import_id="metadata_import_id_value", + ) + + # Make the request + operation = client.create_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_CreateMetadataImport_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_create_service_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_create_service_async.py new file mode 100644 index 0000000..5745292 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_create_service_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateService +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_CreateService_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 metastore_v1 + + +async def sample_create_service(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.CreateServiceRequest( + parent="parent_value", + service_id="service_id_value", + ) + + # Make the request + operation = client.create_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_CreateService_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_create_service_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_create_service_sync.py new file mode 100644 index 0000000..834d1c2 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_create_service_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateService +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_CreateService_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 metastore_v1 + + +def sample_create_service(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.CreateServiceRequest( + parent="parent_value", + service_id="service_id_value", + ) + + # Make the request + operation = client.create_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_CreateService_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_delete_backup_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_delete_backup_async.py new file mode 100644 index 0000000..9ef02b0 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_delete_backup_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteBackup +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_DeleteBackup_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 metastore_v1 + + +async def sample_delete_backup(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_DeleteBackup_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_delete_backup_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_delete_backup_sync.py new file mode 100644 index 0000000..c778e38 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_delete_backup_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteBackup +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_DeleteBackup_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 metastore_v1 + + +def sample_delete_backup(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_DeleteBackup_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_delete_service_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_delete_service_async.py new file mode 100644 index 0000000..b7fa01c --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_delete_service_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteService +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_DeleteService_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 metastore_v1 + + +async def sample_delete_service(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.DeleteServiceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_DeleteService_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_delete_service_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_delete_service_sync.py new file mode 100644 index 0000000..eb60bd1 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_delete_service_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteService +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_DeleteService_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 metastore_v1 + + +def sample_delete_service(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.DeleteServiceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_DeleteService_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_export_metadata_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_export_metadata_async.py new file mode 100644 index 0000000..c953b07 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_export_metadata_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExportMetadata +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_ExportMetadata_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 metastore_v1 + + +async def sample_export_metadata(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.ExportMetadataRequest( + destination_gcs_folder="destination_gcs_folder_value", + service="service_value", + ) + + # Make the request + operation = client.export_metadata(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_ExportMetadata_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_export_metadata_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_export_metadata_sync.py new file mode 100644 index 0000000..7ad998d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_export_metadata_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExportMetadata +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_ExportMetadata_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 metastore_v1 + + +def sample_export_metadata(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.ExportMetadataRequest( + destination_gcs_folder="destination_gcs_folder_value", + service="service_value", + ) + + # Make the request + operation = client.export_metadata(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_ExportMetadata_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_create_federation_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_create_federation_async.py new file mode 100644 index 0000000..b37f7c4 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_create_federation_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateFederation +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastoreFederation_CreateFederation_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 metastore_v1 + + +async def sample_create_federation(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.CreateFederationRequest( + parent="parent_value", + federation_id="federation_id_value", + ) + + # Make the request + operation = client.create_federation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastoreFederation_CreateFederation_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_create_federation_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_create_federation_sync.py new file mode 100644 index 0000000..3ab09fb --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_create_federation_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateFederation +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastoreFederation_CreateFederation_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 metastore_v1 + + +def sample_create_federation(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1.CreateFederationRequest( + parent="parent_value", + federation_id="federation_id_value", + ) + + # Make the request + operation = client.create_federation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastoreFederation_CreateFederation_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_delete_federation_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_delete_federation_async.py new file mode 100644 index 0000000..7e2111b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_delete_federation_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteFederation +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastoreFederation_DeleteFederation_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 metastore_v1 + + +async def sample_delete_federation(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.DeleteFederationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_federation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastoreFederation_DeleteFederation_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_delete_federation_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_delete_federation_sync.py new file mode 100644 index 0000000..8894355 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_delete_federation_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteFederation +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastoreFederation_DeleteFederation_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 metastore_v1 + + +def sample_delete_federation(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1.DeleteFederationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_federation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastoreFederation_DeleteFederation_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_get_federation_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_get_federation_async.py new file mode 100644 index 0000000..32eb62c --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_get_federation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFederation +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastoreFederation_GetFederation_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 metastore_v1 + + +async def sample_get_federation(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.GetFederationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_federation(request=request) + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastoreFederation_GetFederation_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_get_federation_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_get_federation_sync.py new file mode 100644 index 0000000..0fcfb47 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_get_federation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFederation +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastoreFederation_GetFederation_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 metastore_v1 + + +def sample_get_federation(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1.GetFederationRequest( + name="name_value", + ) + + # Make the request + response = client.get_federation(request=request) + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastoreFederation_GetFederation_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_list_federations_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_list_federations_async.py new file mode 100644 index 0000000..022d09a --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_list_federations_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListFederations +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastoreFederation_ListFederations_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 metastore_v1 + + +async def sample_list_federations(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.ListFederationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_federations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END metastore_v1_generated_DataprocMetastoreFederation_ListFederations_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_list_federations_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_list_federations_sync.py new file mode 100644 index 0000000..7870e25 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_list_federations_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListFederations +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastoreFederation_ListFederations_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 metastore_v1 + + +def sample_list_federations(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1.ListFederationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_federations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END metastore_v1_generated_DataprocMetastoreFederation_ListFederations_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_update_federation_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_update_federation_async.py new file mode 100644 index 0000000..968cc28 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_update_federation_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateFederation +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastoreFederation_UpdateFederation_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 metastore_v1 + + +async def sample_update_federation(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.UpdateFederationRequest( + ) + + # Make the request + operation = client.update_federation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastoreFederation_UpdateFederation_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_update_federation_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_update_federation_sync.py new file mode 100644 index 0000000..19d562d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_federation_update_federation_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateFederation +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastoreFederation_UpdateFederation_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 metastore_v1 + + +def sample_update_federation(): + # Create a client + client = metastore_v1.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1.UpdateFederationRequest( + ) + + # Make the request + operation = client.update_federation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastoreFederation_UpdateFederation_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_get_backup_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_get_backup_async.py new file mode 100644 index 0000000..2a5b5b6 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_get_backup_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBackup +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_GetBackup_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 metastore_v1 + + +async def sample_get_backup(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup(request=request) + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_GetBackup_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_get_backup_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_get_backup_sync.py new file mode 100644 index 0000000..130627f --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_get_backup_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBackup +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_GetBackup_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 metastore_v1 + + +def sample_get_backup(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup(request=request) + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_GetBackup_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_get_metadata_import_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_get_metadata_import_async.py new file mode 100644 index 0000000..2b47559 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_get_metadata_import_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMetadataImport +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_GetMetadataImport_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 metastore_v1 + + +async def sample_get_metadata_import(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.GetMetadataImportRequest( + name="name_value", + ) + + # Make the request + response = await client.get_metadata_import(request=request) + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_GetMetadataImport_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_get_metadata_import_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_get_metadata_import_sync.py new file mode 100644 index 0000000..a8405ac --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_get_metadata_import_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMetadataImport +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_GetMetadataImport_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 metastore_v1 + + +def sample_get_metadata_import(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.GetMetadataImportRequest( + name="name_value", + ) + + # Make the request + response = client.get_metadata_import(request=request) + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_GetMetadataImport_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_get_service_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_get_service_async.py new file mode 100644 index 0000000..fb7eb80 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_get_service_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetService +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_GetService_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 metastore_v1 + + +async def sample_get_service(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.GetServiceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_service(request=request) + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_GetService_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_get_service_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_get_service_sync.py new file mode 100644 index 0000000..b6f159d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_get_service_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetService +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_GetService_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 metastore_v1 + + +def sample_get_service(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.GetServiceRequest( + name="name_value", + ) + + # Make the request + response = client.get_service(request=request) + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_GetService_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_list_backups_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_list_backups_async.py new file mode 100644 index 0000000..195a24e --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_list_backups_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBackups +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_ListBackups_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 metastore_v1 + + +async def sample_list_backups(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END metastore_v1_generated_DataprocMetastore_ListBackups_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_list_backups_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_list_backups_sync.py new file mode 100644 index 0000000..f8d6e87 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_list_backups_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBackups +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_ListBackups_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 metastore_v1 + + +def sample_list_backups(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END metastore_v1_generated_DataprocMetastore_ListBackups_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_list_metadata_imports_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_list_metadata_imports_async.py new file mode 100644 index 0000000..607070a --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_list_metadata_imports_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMetadataImports +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_ListMetadataImports_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 metastore_v1 + + +async def sample_list_metadata_imports(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.ListMetadataImportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_metadata_imports(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END metastore_v1_generated_DataprocMetastore_ListMetadataImports_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_list_metadata_imports_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_list_metadata_imports_sync.py new file mode 100644 index 0000000..ccd7e8b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_list_metadata_imports_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMetadataImports +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_ListMetadataImports_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 metastore_v1 + + +def sample_list_metadata_imports(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.ListMetadataImportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_metadata_imports(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END metastore_v1_generated_DataprocMetastore_ListMetadataImports_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_list_services_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_list_services_async.py new file mode 100644 index 0000000..49bb65b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_list_services_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServices +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_ListServices_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 metastore_v1 + + +async def sample_list_services(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.ListServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END metastore_v1_generated_DataprocMetastore_ListServices_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_list_services_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_list_services_sync.py new file mode 100644 index 0000000..bd44a5d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_list_services_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServices +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_ListServices_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 metastore_v1 + + +def sample_list_services(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.ListServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END metastore_v1_generated_DataprocMetastore_ListServices_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_restore_service_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_restore_service_async.py new file mode 100644 index 0000000..b849711 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_restore_service_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreService +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_RestoreService_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 metastore_v1 + + +async def sample_restore_service(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.RestoreServiceRequest( + service="service_value", + backup="backup_value", + ) + + # Make the request + operation = client.restore_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_RestoreService_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_restore_service_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_restore_service_sync.py new file mode 100644 index 0000000..18bc577 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_restore_service_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreService +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_RestoreService_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 metastore_v1 + + +def sample_restore_service(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.RestoreServiceRequest( + service="service_value", + backup="backup_value", + ) + + # Make the request + operation = client.restore_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_RestoreService_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_update_metadata_import_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_update_metadata_import_async.py new file mode 100644 index 0000000..4175af0 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_update_metadata_import_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMetadataImport +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_UpdateMetadataImport_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 metastore_v1 + + +async def sample_update_metadata_import(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.UpdateMetadataImportRequest( + ) + + # Make the request + operation = client.update_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_UpdateMetadataImport_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_update_metadata_import_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_update_metadata_import_sync.py new file mode 100644 index 0000000..28a7d91 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_update_metadata_import_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMetadataImport +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_UpdateMetadataImport_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 metastore_v1 + + +def sample_update_metadata_import(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.UpdateMetadataImportRequest( + ) + + # Make the request + operation = client.update_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_UpdateMetadataImport_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_update_service_async.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_update_service_async.py new file mode 100644 index 0000000..b9f8cad --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_update_service_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateService +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_UpdateService_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 metastore_v1 + + +async def sample_update_service(): + # Create a client + client = metastore_v1.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1.UpdateServiceRequest( + ) + + # Make the request + operation = client.update_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_UpdateService_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_update_service_sync.py b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_update_service_sync.py new file mode 100644 index 0000000..c1c2e3b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/metastore_v1_generated_dataproc_metastore_update_service_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateService +# 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-dataproc-metastore + + +# [START metastore_v1_generated_DataprocMetastore_UpdateService_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 metastore_v1 + + +def sample_update_service(): + # Create a client + client = metastore_v1.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1.UpdateServiceRequest( + ) + + # Make the request + operation = client.update_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1_generated_DataprocMetastore_UpdateService_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1.json new file mode 100644 index 0000000..f1638aa --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1.json @@ -0,0 +1,3323 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.metastore.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-dataproc-metastore", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationAsyncClient", + "shortName": "DataprocMetastoreFederationAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationAsyncClient.create_federation", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation.CreateFederation", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "CreateFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.CreateFederationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "federation", + "type": "google.cloud.metastore_v1.types.Federation" + }, + { + "name": "federation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_federation" + }, + "description": "Sample for CreateFederation", + "file": "metastore_v1_generated_dataproc_metastore_federation_create_federation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastoreFederation_CreateFederation_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_federation_create_federation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationClient", + "shortName": "DataprocMetastoreFederationClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationClient.create_federation", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation.CreateFederation", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "CreateFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.CreateFederationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "federation", + "type": "google.cloud.metastore_v1.types.Federation" + }, + { + "name": "federation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_federation" + }, + "description": "Sample for CreateFederation", + "file": "metastore_v1_generated_dataproc_metastore_federation_create_federation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastoreFederation_CreateFederation_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_federation_create_federation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationAsyncClient", + "shortName": "DataprocMetastoreFederationAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationAsyncClient.delete_federation", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation.DeleteFederation", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "DeleteFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.DeleteFederationRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "delete_federation" + }, + "description": "Sample for DeleteFederation", + "file": "metastore_v1_generated_dataproc_metastore_federation_delete_federation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastoreFederation_DeleteFederation_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_federation_delete_federation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationClient", + "shortName": "DataprocMetastoreFederationClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationClient.delete_federation", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation.DeleteFederation", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "DeleteFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.DeleteFederationRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "delete_federation" + }, + "description": "Sample for DeleteFederation", + "file": "metastore_v1_generated_dataproc_metastore_federation_delete_federation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastoreFederation_DeleteFederation_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_federation_delete_federation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationAsyncClient", + "shortName": "DataprocMetastoreFederationAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationAsyncClient.get_federation", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation.GetFederation", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "GetFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.GetFederationRequest" + }, + { + "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.metastore_v1.types.Federation", + "shortName": "get_federation" + }, + "description": "Sample for GetFederation", + "file": "metastore_v1_generated_dataproc_metastore_federation_get_federation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastoreFederation_GetFederation_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": "metastore_v1_generated_dataproc_metastore_federation_get_federation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationClient", + "shortName": "DataprocMetastoreFederationClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationClient.get_federation", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation.GetFederation", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "GetFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.GetFederationRequest" + }, + { + "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.metastore_v1.types.Federation", + "shortName": "get_federation" + }, + "description": "Sample for GetFederation", + "file": "metastore_v1_generated_dataproc_metastore_federation_get_federation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastoreFederation_GetFederation_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": "metastore_v1_generated_dataproc_metastore_federation_get_federation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationAsyncClient", + "shortName": "DataprocMetastoreFederationAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationAsyncClient.list_federations", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation.ListFederations", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "ListFederations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.ListFederationsRequest" + }, + { + "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.metastore_v1.services.dataproc_metastore_federation.pagers.ListFederationsAsyncPager", + "shortName": "list_federations" + }, + "description": "Sample for ListFederations", + "file": "metastore_v1_generated_dataproc_metastore_federation_list_federations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastoreFederation_ListFederations_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": "metastore_v1_generated_dataproc_metastore_federation_list_federations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationClient", + "shortName": "DataprocMetastoreFederationClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationClient.list_federations", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation.ListFederations", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "ListFederations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.ListFederationsRequest" + }, + { + "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.metastore_v1.services.dataproc_metastore_federation.pagers.ListFederationsPager", + "shortName": "list_federations" + }, + "description": "Sample for ListFederations", + "file": "metastore_v1_generated_dataproc_metastore_federation_list_federations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastoreFederation_ListFederations_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": "metastore_v1_generated_dataproc_metastore_federation_list_federations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationAsyncClient", + "shortName": "DataprocMetastoreFederationAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationAsyncClient.update_federation", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation.UpdateFederation", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "UpdateFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.UpdateFederationRequest" + }, + { + "name": "federation", + "type": "google.cloud.metastore_v1.types.Federation" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "update_federation" + }, + "description": "Sample for UpdateFederation", + "file": "metastore_v1_generated_dataproc_metastore_federation_update_federation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastoreFederation_UpdateFederation_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_federation_update_federation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationClient", + "shortName": "DataprocMetastoreFederationClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreFederationClient.update_federation", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation.UpdateFederation", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "UpdateFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.UpdateFederationRequest" + }, + { + "name": "federation", + "type": "google.cloud.metastore_v1.types.Federation" + }, + { + "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.api_core.operation.Operation", + "shortName": "update_federation" + }, + "description": "Sample for UpdateFederation", + "file": "metastore_v1_generated_dataproc_metastore_federation_update_federation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastoreFederation_UpdateFederation_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_federation_update_federation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient.create_backup", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.CreateBackup", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "CreateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.CreateBackupRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup", + "type": "google.cloud.metastore_v1.types.Backup" + }, + { + "name": "backup_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_backup" + }, + "description": "Sample for CreateBackup", + "file": "metastore_v1_generated_dataproc_metastore_create_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_CreateBackup_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_create_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient.create_backup", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.CreateBackup", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "CreateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.CreateBackupRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup", + "type": "google.cloud.metastore_v1.types.Backup" + }, + { + "name": "backup_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_backup" + }, + "description": "Sample for CreateBackup", + "file": "metastore_v1_generated_dataproc_metastore_create_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_CreateBackup_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_create_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient.create_metadata_import", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.CreateMetadataImport", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "CreateMetadataImport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.CreateMetadataImportRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "metadata_import", + "type": "google.cloud.metastore_v1.types.MetadataImport" + }, + { + "name": "metadata_import_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_metadata_import" + }, + "description": "Sample for CreateMetadataImport", + "file": "metastore_v1_generated_dataproc_metastore_create_metadata_import_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_CreateMetadataImport_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_create_metadata_import_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient.create_metadata_import", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.CreateMetadataImport", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "CreateMetadataImport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.CreateMetadataImportRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "metadata_import", + "type": "google.cloud.metastore_v1.types.MetadataImport" + }, + { + "name": "metadata_import_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_metadata_import" + }, + "description": "Sample for CreateMetadataImport", + "file": "metastore_v1_generated_dataproc_metastore_create_metadata_import_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_CreateMetadataImport_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_create_metadata_import_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient.create_service", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.CreateService", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "CreateService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.CreateServiceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "service", + "type": "google.cloud.metastore_v1.types.Service" + }, + { + "name": "service_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_service" + }, + "description": "Sample for CreateService", + "file": "metastore_v1_generated_dataproc_metastore_create_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_CreateService_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_create_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient.create_service", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.CreateService", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "CreateService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.CreateServiceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "service", + "type": "google.cloud.metastore_v1.types.Service" + }, + { + "name": "service_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_service" + }, + "description": "Sample for CreateService", + "file": "metastore_v1_generated_dataproc_metastore_create_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_CreateService_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_create_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient.delete_backup", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.DeleteBackup", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.DeleteBackupRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "delete_backup" + }, + "description": "Sample for DeleteBackup", + "file": "metastore_v1_generated_dataproc_metastore_delete_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_DeleteBackup_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_delete_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient.delete_backup", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.DeleteBackup", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.DeleteBackupRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "delete_backup" + }, + "description": "Sample for DeleteBackup", + "file": "metastore_v1_generated_dataproc_metastore_delete_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_DeleteBackup_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_delete_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient.delete_service", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.DeleteService", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "DeleteService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.DeleteServiceRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "delete_service" + }, + "description": "Sample for DeleteService", + "file": "metastore_v1_generated_dataproc_metastore_delete_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_DeleteService_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_delete_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient.delete_service", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.DeleteService", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "DeleteService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.DeleteServiceRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "delete_service" + }, + "description": "Sample for DeleteService", + "file": "metastore_v1_generated_dataproc_metastore_delete_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_DeleteService_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_delete_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient.export_metadata", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.ExportMetadata", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ExportMetadata" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.ExportMetadataRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "export_metadata" + }, + "description": "Sample for ExportMetadata", + "file": "metastore_v1_generated_dataproc_metastore_export_metadata_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_ExportMetadata_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_export_metadata_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient.export_metadata", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.ExportMetadata", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ExportMetadata" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.ExportMetadataRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "export_metadata" + }, + "description": "Sample for ExportMetadata", + "file": "metastore_v1_generated_dataproc_metastore_export_metadata_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_ExportMetadata_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_export_metadata_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient.get_backup", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.GetBackup", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.GetBackupRequest" + }, + { + "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.metastore_v1.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "metastore_v1_generated_dataproc_metastore_get_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_GetBackup_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": "metastore_v1_generated_dataproc_metastore_get_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient.get_backup", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.GetBackup", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.GetBackupRequest" + }, + { + "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.metastore_v1.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "metastore_v1_generated_dataproc_metastore_get_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_GetBackup_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": "metastore_v1_generated_dataproc_metastore_get_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient.get_metadata_import", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.GetMetadataImport", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "GetMetadataImport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.GetMetadataImportRequest" + }, + { + "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.metastore_v1.types.MetadataImport", + "shortName": "get_metadata_import" + }, + "description": "Sample for GetMetadataImport", + "file": "metastore_v1_generated_dataproc_metastore_get_metadata_import_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_GetMetadataImport_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": "metastore_v1_generated_dataproc_metastore_get_metadata_import_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient.get_metadata_import", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.GetMetadataImport", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "GetMetadataImport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.GetMetadataImportRequest" + }, + { + "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.metastore_v1.types.MetadataImport", + "shortName": "get_metadata_import" + }, + "description": "Sample for GetMetadataImport", + "file": "metastore_v1_generated_dataproc_metastore_get_metadata_import_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_GetMetadataImport_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": "metastore_v1_generated_dataproc_metastore_get_metadata_import_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient.get_service", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.GetService", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "GetService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.GetServiceRequest" + }, + { + "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.metastore_v1.types.Service", + "shortName": "get_service" + }, + "description": "Sample for GetService", + "file": "metastore_v1_generated_dataproc_metastore_get_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_GetService_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": "metastore_v1_generated_dataproc_metastore_get_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient.get_service", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.GetService", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "GetService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.GetServiceRequest" + }, + { + "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.metastore_v1.types.Service", + "shortName": "get_service" + }, + "description": "Sample for GetService", + "file": "metastore_v1_generated_dataproc_metastore_get_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_GetService_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": "metastore_v1_generated_dataproc_metastore_get_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient.list_backups", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.ListBackups", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ListBackups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.ListBackupsRequest" + }, + { + "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.metastore_v1.services.dataproc_metastore.pagers.ListBackupsAsyncPager", + "shortName": "list_backups" + }, + "description": "Sample for ListBackups", + "file": "metastore_v1_generated_dataproc_metastore_list_backups_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_ListBackups_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": "metastore_v1_generated_dataproc_metastore_list_backups_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient.list_backups", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.ListBackups", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ListBackups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.ListBackupsRequest" + }, + { + "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.metastore_v1.services.dataproc_metastore.pagers.ListBackupsPager", + "shortName": "list_backups" + }, + "description": "Sample for ListBackups", + "file": "metastore_v1_generated_dataproc_metastore_list_backups_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_ListBackups_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": "metastore_v1_generated_dataproc_metastore_list_backups_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient.list_metadata_imports", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.ListMetadataImports", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ListMetadataImports" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.ListMetadataImportsRequest" + }, + { + "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.metastore_v1.services.dataproc_metastore.pagers.ListMetadataImportsAsyncPager", + "shortName": "list_metadata_imports" + }, + "description": "Sample for ListMetadataImports", + "file": "metastore_v1_generated_dataproc_metastore_list_metadata_imports_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_ListMetadataImports_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": "metastore_v1_generated_dataproc_metastore_list_metadata_imports_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient.list_metadata_imports", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.ListMetadataImports", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ListMetadataImports" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.ListMetadataImportsRequest" + }, + { + "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.metastore_v1.services.dataproc_metastore.pagers.ListMetadataImportsPager", + "shortName": "list_metadata_imports" + }, + "description": "Sample for ListMetadataImports", + "file": "metastore_v1_generated_dataproc_metastore_list_metadata_imports_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_ListMetadataImports_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": "metastore_v1_generated_dataproc_metastore_list_metadata_imports_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient.list_services", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.ListServices", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ListServices" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.ListServicesRequest" + }, + { + "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.metastore_v1.services.dataproc_metastore.pagers.ListServicesAsyncPager", + "shortName": "list_services" + }, + "description": "Sample for ListServices", + "file": "metastore_v1_generated_dataproc_metastore_list_services_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_ListServices_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": "metastore_v1_generated_dataproc_metastore_list_services_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient.list_services", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.ListServices", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ListServices" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.ListServicesRequest" + }, + { + "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.metastore_v1.services.dataproc_metastore.pagers.ListServicesPager", + "shortName": "list_services" + }, + "description": "Sample for ListServices", + "file": "metastore_v1_generated_dataproc_metastore_list_services_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_ListServices_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": "metastore_v1_generated_dataproc_metastore_list_services_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient.restore_service", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.RestoreService", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "RestoreService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.RestoreServiceRequest" + }, + { + "name": "service", + "type": "str" + }, + { + "name": "backup", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "restore_service" + }, + "description": "Sample for RestoreService", + "file": "metastore_v1_generated_dataproc_metastore_restore_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_RestoreService_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_restore_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient.restore_service", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.RestoreService", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "RestoreService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.RestoreServiceRequest" + }, + { + "name": "service", + "type": "str" + }, + { + "name": "backup", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "restore_service" + }, + "description": "Sample for RestoreService", + "file": "metastore_v1_generated_dataproc_metastore_restore_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_RestoreService_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_restore_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient.update_metadata_import", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.UpdateMetadataImport", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "UpdateMetadataImport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.UpdateMetadataImportRequest" + }, + { + "name": "metadata_import", + "type": "google.cloud.metastore_v1.types.MetadataImport" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "update_metadata_import" + }, + "description": "Sample for UpdateMetadataImport", + "file": "metastore_v1_generated_dataproc_metastore_update_metadata_import_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_UpdateMetadataImport_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_update_metadata_import_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient.update_metadata_import", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.UpdateMetadataImport", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "UpdateMetadataImport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.UpdateMetadataImportRequest" + }, + { + "name": "metadata_import", + "type": "google.cloud.metastore_v1.types.MetadataImport" + }, + { + "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.api_core.operation.Operation", + "shortName": "update_metadata_import" + }, + "description": "Sample for UpdateMetadataImport", + "file": "metastore_v1_generated_dataproc_metastore_update_metadata_import_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_UpdateMetadataImport_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_update_metadata_import_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreAsyncClient.update_service", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.UpdateService", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "UpdateService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.UpdateServiceRequest" + }, + { + "name": "service", + "type": "google.cloud.metastore_v1.types.Service" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "update_service" + }, + "description": "Sample for UpdateService", + "file": "metastore_v1_generated_dataproc_metastore_update_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_UpdateService_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_update_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1.DataprocMetastoreClient.update_service", + "method": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore.UpdateService", + "service": { + "fullName": "google.cloud.metastore.v1.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "UpdateService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1.types.UpdateServiceRequest" + }, + { + "name": "service", + "type": "google.cloud.metastore_v1.types.Service" + }, + { + "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.api_core.operation.Operation", + "shortName": "update_service" + }, + "description": "Sample for UpdateService", + "file": "metastore_v1_generated_dataproc_metastore_update_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1_generated_DataprocMetastore_UpdateService_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1_generated_dataproc_metastore_update_service_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1/scripts/fixup_metastore_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_metastore_v1_keywords.py new file mode 100644 index 0000000..cbca0a7 --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_metastore_v1_keywords.py @@ -0,0 +1,195 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class metastoreCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_backup': ('parent', 'backup_id', 'backup', 'request_id', ), + 'create_federation': ('parent', 'federation_id', 'federation', 'request_id', ), + 'create_metadata_import': ('parent', 'metadata_import_id', 'metadata_import', 'request_id', ), + 'create_service': ('parent', 'service_id', 'service', 'request_id', ), + 'delete_backup': ('name', 'request_id', ), + 'delete_federation': ('name', 'request_id', ), + 'delete_service': ('name', 'request_id', ), + 'export_metadata': ('service', 'destination_gcs_folder', 'request_id', 'database_dump_type', ), + 'get_backup': ('name', ), + 'get_federation': ('name', ), + 'get_metadata_import': ('name', ), + 'get_service': ('name', ), + 'list_backups': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_federations': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_metadata_imports': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_services': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'restore_service': ('service', 'backup', 'restore_type', 'request_id', ), + 'update_federation': ('update_mask', 'federation', 'request_id', ), + 'update_metadata_import': ('update_mask', 'metadata_import', 'request_id', ), + 'update_service': ('update_mask', 'service', '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=metastoreCallTransformer(), +): + """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 metastore 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/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 0000000..3b0acfa --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-dataproc-metastore' + + +description = "Google Cloud Dataproc Metastore API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/metastore/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", + "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", +] +url = "https://github.com/googleapis/python-dataproc-metastore" + +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/v1/testing/constraints-3.10.txt b/owl-bot-staging/v1/testing/constraints-3.10.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/testing/constraints-3.11.txt b/owl-bot-staging/v1/testing/constraints-3.11.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/testing/constraints-3.12.txt b/owl-bot-staging/v1/testing/constraints-3.12.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/testing/constraints-3.7.txt b/owl-bot-staging/v1/testing/constraints-3.7.txt new file mode 100644 index 0000000..2beecf9 --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 +grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/v1/testing/constraints-3.8.txt b/owl-bot-staging/v1/testing/constraints-3.8.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/testing/constraints-3.9.txt b/owl-bot-staging/v1/testing/constraints-3.9.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/metastore_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/metastore_v1/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/metastore_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/metastore_v1/test_dataproc_metastore.py b/owl-bot-staging/v1/tests/unit/gapic/metastore_v1/test_dataproc_metastore.py new file mode 100644 index 0000000..d5dd308 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/metastore_v1/test_dataproc_metastore.py @@ -0,0 +1,10707 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.metastore_v1.services.dataproc_metastore import DataprocMetastoreAsyncClient +from google.cloud.metastore_v1.services.dataproc_metastore import DataprocMetastoreClient +from google.cloud.metastore_v1.services.dataproc_metastore import pagers +from google.cloud.metastore_v1.services.dataproc_metastore import transports +from google.cloud.metastore_v1.types import metastore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import dayofweek_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 DataprocMetastoreClient._get_default_mtls_endpoint(None) is None + assert DataprocMetastoreClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DataprocMetastoreClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DataprocMetastoreClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DataprocMetastoreClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DataprocMetastoreClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DataprocMetastoreClient, "grpc"), + (DataprocMetastoreAsyncClient, "grpc_asyncio"), + (DataprocMetastoreClient, "rest"), +]) +def test_dataproc_metastore_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 == ( + 'metastore.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://metastore.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DataprocMetastoreGrpcTransport, "grpc"), + (transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DataprocMetastoreRestTransport, "rest"), +]) +def test_dataproc_metastore_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", [ + (DataprocMetastoreClient, "grpc"), + (DataprocMetastoreAsyncClient, "grpc_asyncio"), + (DataprocMetastoreClient, "rest"), +]) +def test_dataproc_metastore_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 == ( + 'metastore.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://metastore.googleapis.com' + ) + + +def test_dataproc_metastore_client_get_transport_class(): + transport = DataprocMetastoreClient.get_transport_class() + available_transports = [ + transports.DataprocMetastoreGrpcTransport, + transports.DataprocMetastoreRestTransport, + ] + assert transport in available_transports + + transport = DataprocMetastoreClient.get_transport_class("grpc") + assert transport == transports.DataprocMetastoreGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport, "grpc"), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio"), + (DataprocMetastoreClient, transports.DataprocMetastoreRestTransport, "rest"), +]) +@mock.patch.object(DataprocMetastoreClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreClient)) +@mock.patch.object(DataprocMetastoreAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreAsyncClient)) +def test_dataproc_metastore_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(DataprocMetastoreClient, '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(DataprocMetastoreClient, '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", [ + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport, "grpc", "true"), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport, "grpc", "false"), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (DataprocMetastoreClient, transports.DataprocMetastoreRestTransport, "rest", "true"), + (DataprocMetastoreClient, transports.DataprocMetastoreRestTransport, "rest", "false"), +]) +@mock.patch.object(DataprocMetastoreClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreClient)) +@mock.patch.object(DataprocMetastoreAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_dataproc_metastore_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", [ + DataprocMetastoreClient, DataprocMetastoreAsyncClient +]) +@mock.patch.object(DataprocMetastoreClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreClient)) +@mock.patch.object(DataprocMetastoreAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreAsyncClient)) +def test_dataproc_metastore_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", [ + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport, "grpc"), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio"), + (DataprocMetastoreClient, transports.DataprocMetastoreRestTransport, "rest"), +]) +def test_dataproc_metastore_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", [ + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport, "grpc", grpc_helpers), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (DataprocMetastoreClient, transports.DataprocMetastoreRestTransport, "rest", None), +]) +def test_dataproc_metastore_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_dataproc_metastore_client_client_options_from_dict(): + with mock.patch('google.cloud.metastore_v1.services.dataproc_metastore.transports.DataprocMetastoreGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DataprocMetastoreClient( + 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", [ + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport, "grpc", grpc_helpers), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_dataproc_metastore_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( + "metastore.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="metastore.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ListServicesRequest, + dict, +]) +def test_list_services(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListServicesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListServicesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_services_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_services), + '__call__') as call: + client.list_services() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListServicesRequest() + +@pytest.mark.asyncio +async def test_list_services_async(transport: str = 'grpc_asyncio', request_type=metastore.ListServicesRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListServicesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListServicesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_services_async_from_dict(): + await test_list_services_async(request_type=dict) + + +def test_list_services_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ListServicesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + call.return_value = metastore.ListServicesResponse() + client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_services_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ListServicesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListServicesResponse()) + await client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_services_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListServicesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_services( + 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_services_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_services( + metastore.ListServicesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_services_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListServicesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListServicesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_services( + 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_services_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_services( + metastore.ListServicesRequest(), + parent='parent_value', + ) + + +def test_list_services_pager(transport_name: str = "grpc"): + client = DataprocMetastoreClient( + 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_services), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + metastore.Service(), + ], + next_page_token='abc', + ), + metastore.ListServicesResponse( + services=[], + next_page_token='def', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + ], + next_page_token='ghi', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_services(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore.Service) + for i in results) +def test_list_services_pages(transport_name: str = "grpc"): + client = DataprocMetastoreClient( + 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_services), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + metastore.Service(), + ], + next_page_token='abc', + ), + metastore.ListServicesResponse( + services=[], + next_page_token='def', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + ], + next_page_token='ghi', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + ], + ), + RuntimeError, + ) + pages = list(client.list_services(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_services_async_pager(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + metastore.Service(), + ], + next_page_token='abc', + ), + metastore.ListServicesResponse( + services=[], + next_page_token='def', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + ], + next_page_token='ghi', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_services(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, metastore.Service) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_services_async_pages(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + metastore.Service(), + ], + next_page_token='abc', + ), + metastore.ListServicesResponse( + services=[], + next_page_token='def', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + ], + next_page_token='ghi', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_services(request={})).pages: # pragma: no branch + 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", [ + metastore.GetServiceRequest, + dict, +]) +def test_get_service(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.Service( + name='name_value', + network='network_value', + endpoint_uri='endpoint_uri_value', + port=453, + state=metastore.Service.State.CREATING, + state_message='state_message_value', + artifact_gcs_uri='artifact_gcs_uri_value', + tier=metastore.Service.Tier.DEVELOPER, + uid='uid_value', + release_channel=metastore.Service.ReleaseChannel.CANARY, + database_type=metastore.Service.DatabaseType.MYSQL, + hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value'), + ) + response = client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.Service) + assert response.name == 'name_value' + assert response.network == 'network_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.port == 453 + assert response.state == metastore.Service.State.CREATING + assert response.state_message == 'state_message_value' + assert response.artifact_gcs_uri == 'artifact_gcs_uri_value' + assert response.tier == metastore.Service.Tier.DEVELOPER + assert response.uid == 'uid_value' + assert response.release_channel == metastore.Service.ReleaseChannel.CANARY + assert response.database_type == metastore.Service.DatabaseType.MYSQL + + +def test_get_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_service), + '__call__') as call: + client.get_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetServiceRequest() + +@pytest.mark.asyncio +async def test_get_service_async(transport: str = 'grpc_asyncio', request_type=metastore.GetServiceRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.Service( + name='name_value', + network='network_value', + endpoint_uri='endpoint_uri_value', + port=453, + state=metastore.Service.State.CREATING, + state_message='state_message_value', + artifact_gcs_uri='artifact_gcs_uri_value', + tier=metastore.Service.Tier.DEVELOPER, + uid='uid_value', + release_channel=metastore.Service.ReleaseChannel.CANARY, + database_type=metastore.Service.DatabaseType.MYSQL, + )) + response = await client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.Service) + assert response.name == 'name_value' + assert response.network == 'network_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.port == 453 + assert response.state == metastore.Service.State.CREATING + assert response.state_message == 'state_message_value' + assert response.artifact_gcs_uri == 'artifact_gcs_uri_value' + assert response.tier == metastore.Service.Tier.DEVELOPER + assert response.uid == 'uid_value' + assert response.release_channel == metastore.Service.ReleaseChannel.CANARY + assert response.database_type == metastore.Service.DatabaseType.MYSQL + + +@pytest.mark.asyncio +async def test_get_service_async_from_dict(): + await test_get_service_async(request_type=dict) + + +def test_get_service_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.GetServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + call.return_value = metastore.Service() + client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_service_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.GetServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.Service()) + await client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_service_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.Service() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_service( + 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_service_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_service( + metastore.GetServiceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_service_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.Service() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.Service()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_service( + 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_service_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_service( + metastore.GetServiceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.CreateServiceRequest, + dict, +]) +def test_create_service(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_service), + '__call__') as call: + client.create_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateServiceRequest() + +@pytest.mark.asyncio +async def test_create_service_async(transport: str = 'grpc_asyncio', request_type=metastore.CreateServiceRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_service_async_from_dict(): + await test_create_service_async(request_type=dict) + + +def test_create_service_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.CreateServiceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_service_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.CreateServiceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_service_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_service( + parent='parent_value', + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + service_id='service_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].service + mock_val = metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')) + assert arg == mock_val + arg = args[0].service_id + mock_val = 'service_id_value' + assert arg == mock_val + + +def test_create_service_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_service( + metastore.CreateServiceRequest(), + parent='parent_value', + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + service_id='service_id_value', + ) + +@pytest.mark.asyncio +async def test_create_service_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_service( + parent='parent_value', + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + service_id='service_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].service + mock_val = metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')) + assert arg == mock_val + arg = args[0].service_id + mock_val = 'service_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_service_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_service( + metastore.CreateServiceRequest(), + parent='parent_value', + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + service_id='service_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.UpdateServiceRequest, + dict, +]) +def test_update_service(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.UpdateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_service), + '__call__') as call: + client.update_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.UpdateServiceRequest() + +@pytest.mark.asyncio +async def test_update_service_async(transport: str = 'grpc_asyncio', request_type=metastore.UpdateServiceRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.UpdateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_service_async_from_dict(): + await test_update_service_async(request_type=dict) + + +def test_update_service_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.UpdateServiceRequest() + + request.service.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_service_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.UpdateServiceRequest() + + request.service.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service.name=name_value', + ) in kw['metadata'] + + +def test_update_service_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_service( + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_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].service + mock_val = metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_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_service_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_service( + metastore.UpdateServiceRequest(), + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_service_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_service( + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_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].service + mock_val = metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_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_service_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_service( + metastore.UpdateServiceRequest(), + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.DeleteServiceRequest, + dict, +]) +def test_delete_service(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.DeleteServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_service), + '__call__') as call: + client.delete_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.DeleteServiceRequest() + +@pytest.mark.asyncio +async def test_delete_service_async(transport: str = 'grpc_asyncio', request_type=metastore.DeleteServiceRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.DeleteServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_service_async_from_dict(): + await test_delete_service_async(request_type=dict) + + +def test_delete_service_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.DeleteServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_service_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.DeleteServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_service_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_service( + 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_service_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_service( + metastore.DeleteServiceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_service_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_service( + 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_service_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_service( + metastore.DeleteServiceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ListMetadataImportsRequest, + dict, +]) +def test_list_metadata_imports(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata_imports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListMetadataImportsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_metadata_imports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListMetadataImportsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMetadataImportsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_metadata_imports_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_metadata_imports), + '__call__') as call: + client.list_metadata_imports() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListMetadataImportsRequest() + +@pytest.mark.asyncio +async def test_list_metadata_imports_async(transport: str = 'grpc_asyncio', request_type=metastore.ListMetadataImportsRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata_imports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListMetadataImportsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_metadata_imports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListMetadataImportsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMetadataImportsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_metadata_imports_async_from_dict(): + await test_list_metadata_imports_async(request_type=dict) + + +def test_list_metadata_imports_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ListMetadataImportsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_metadata_imports), + '__call__') as call: + call.return_value = metastore.ListMetadataImportsResponse() + client.list_metadata_imports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_metadata_imports_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ListMetadataImportsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_metadata_imports), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListMetadataImportsResponse()) + await client.list_metadata_imports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_metadata_imports_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_metadata_imports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListMetadataImportsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_metadata_imports( + 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_metadata_imports_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_metadata_imports( + metastore.ListMetadataImportsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_metadata_imports_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_metadata_imports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListMetadataImportsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListMetadataImportsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_metadata_imports( + 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_metadata_imports_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_metadata_imports( + metastore.ListMetadataImportsRequest(), + parent='parent_value', + ) + + +def test_list_metadata_imports_pager(transport_name: str = "grpc"): + client = DataprocMetastoreClient( + 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_metadata_imports), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + next_page_token='abc', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[], + next_page_token='def', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + ], + next_page_token='ghi', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_metadata_imports(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore.MetadataImport) + for i in results) +def test_list_metadata_imports_pages(transport_name: str = "grpc"): + client = DataprocMetastoreClient( + 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_metadata_imports), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + next_page_token='abc', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[], + next_page_token='def', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + ], + next_page_token='ghi', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + ), + RuntimeError, + ) + pages = list(client.list_metadata_imports(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_metadata_imports_async_pager(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_metadata_imports), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + next_page_token='abc', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[], + next_page_token='def', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + ], + next_page_token='ghi', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_metadata_imports(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, metastore.MetadataImport) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_metadata_imports_async_pages(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_metadata_imports), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + next_page_token='abc', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[], + next_page_token='def', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + ], + next_page_token='ghi', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_metadata_imports(request={})).pages: # pragma: no branch + 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", [ + metastore.GetMetadataImportRequest, + dict, +]) +def test_get_metadata_import(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.MetadataImport( + name='name_value', + description='description_value', + state=metastore.MetadataImport.State.RUNNING, + database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL), + ) + response = client.get_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetMetadataImportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.MetadataImport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == metastore.MetadataImport.State.RUNNING + + +def test_get_metadata_import_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + client.get_metadata_import() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetMetadataImportRequest() + +@pytest.mark.asyncio +async def test_get_metadata_import_async(transport: str = 'grpc_asyncio', request_type=metastore.GetMetadataImportRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.MetadataImport( + name='name_value', + description='description_value', + state=metastore.MetadataImport.State.RUNNING, + )) + response = await client.get_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetMetadataImportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.MetadataImport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == metastore.MetadataImport.State.RUNNING + + +@pytest.mark.asyncio +async def test_get_metadata_import_async_from_dict(): + await test_get_metadata_import_async(request_type=dict) + + +def test_get_metadata_import_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.GetMetadataImportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + call.return_value = metastore.MetadataImport() + client.get_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_metadata_import_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.GetMetadataImportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.MetadataImport()) + await client.get_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_metadata_import_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.MetadataImport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_metadata_import( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_metadata_import_flattened_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_metadata_import( + metastore.GetMetadataImportRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_metadata_import_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.MetadataImport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.MetadataImport()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_metadata_import( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_metadata_import_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_metadata_import( + metastore.GetMetadataImportRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.CreateMetadataImportRequest, + dict, +]) +def test_create_metadata_import(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateMetadataImportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_metadata_import_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_metadata_import), + '__call__') as call: + client.create_metadata_import() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateMetadataImportRequest() + +@pytest.mark.asyncio +async def test_create_metadata_import_async(transport: str = 'grpc_asyncio', request_type=metastore.CreateMetadataImportRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateMetadataImportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_metadata_import_async_from_dict(): + await test_create_metadata_import_async(request_type=dict) + + +def test_create_metadata_import_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.CreateMetadataImportRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_metadata_import), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_metadata_import_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.CreateMetadataImportRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_metadata_import), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_metadata_import_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_metadata_import( + parent='parent_value', + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + metadata_import_id='metadata_import_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].metadata_import + mock_val = metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)) + assert arg == mock_val + arg = args[0].metadata_import_id + mock_val = 'metadata_import_id_value' + assert arg == mock_val + + +def test_create_metadata_import_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_metadata_import( + metastore.CreateMetadataImportRequest(), + parent='parent_value', + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + metadata_import_id='metadata_import_id_value', + ) + +@pytest.mark.asyncio +async def test_create_metadata_import_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_metadata_import( + parent='parent_value', + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + metadata_import_id='metadata_import_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].metadata_import + mock_val = metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)) + assert arg == mock_val + arg = args[0].metadata_import_id + mock_val = 'metadata_import_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_metadata_import_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_metadata_import( + metastore.CreateMetadataImportRequest(), + parent='parent_value', + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + metadata_import_id='metadata_import_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.UpdateMetadataImportRequest, + dict, +]) +def test_update_metadata_import(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.UpdateMetadataImportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_metadata_import_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_metadata_import), + '__call__') as call: + client.update_metadata_import() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.UpdateMetadataImportRequest() + +@pytest.mark.asyncio +async def test_update_metadata_import_async(transport: str = 'grpc_asyncio', request_type=metastore.UpdateMetadataImportRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.UpdateMetadataImportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_metadata_import_async_from_dict(): + await test_update_metadata_import_async(request_type=dict) + + +def test_update_metadata_import_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.UpdateMetadataImportRequest() + + request.metadata_import.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_metadata_import), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'metadata_import.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_metadata_import_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.UpdateMetadataImportRequest() + + request.metadata_import.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_metadata_import), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'metadata_import.name=name_value', + ) in kw['metadata'] + + +def test_update_metadata_import_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_metadata_import( + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + 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].metadata_import + mock_val = metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)) + 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_metadata_import_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_metadata_import( + metastore.UpdateMetadataImportRequest(), + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_metadata_import_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_metadata_import( + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + 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].metadata_import + mock_val = metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)) + 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_metadata_import_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_metadata_import( + metastore.UpdateMetadataImportRequest(), + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ExportMetadataRequest, + dict, +]) +def test_export_metadata(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.export_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ExportMetadataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_metadata_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_metadata), + '__call__') as call: + client.export_metadata() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ExportMetadataRequest() + +@pytest.mark.asyncio +async def test_export_metadata_async(transport: str = 'grpc_asyncio', request_type=metastore.ExportMetadataRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.export_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ExportMetadataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_export_metadata_async_from_dict(): + await test_export_metadata_async(request_type=dict) + + +def test_export_metadata_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ExportMetadataRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_metadata), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.export_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_export_metadata_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ExportMetadataRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_metadata), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.export_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + metastore.RestoreServiceRequest, + dict, +]) +def test_restore_service(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.restore_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.RestoreServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_restore_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + client.restore_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.RestoreServiceRequest() + +@pytest.mark.asyncio +async def test_restore_service_async(transport: str = 'grpc_asyncio', request_type=metastore.RestoreServiceRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.restore_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.RestoreServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_restore_service_async_from_dict(): + await test_restore_service_async(request_type=dict) + + +def test_restore_service_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.RestoreServiceRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.restore_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_restore_service_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.RestoreServiceRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.restore_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +def test_restore_service_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.restore_service( + service='service_value', + backup='backup_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].service + mock_val = 'service_value' + assert arg == mock_val + arg = args[0].backup + mock_val = 'backup_value' + assert arg == mock_val + + +def test_restore_service_flattened_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restore_service( + metastore.RestoreServiceRequest(), + service='service_value', + backup='backup_value', + ) + +@pytest.mark.asyncio +async def test_restore_service_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.restore_service( + service='service_value', + backup='backup_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].service + mock_val = 'service_value' + assert arg == mock_val + arg = args[0].backup + mock_val = 'backup_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_restore_service_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.restore_service( + metastore.RestoreServiceRequest(), + service='service_value', + backup='backup_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ListBackupsRequest, + dict, +]) +def test_list_backups(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListBackupsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListBackupsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_backups_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_backups), + '__call__') as call: + client.list_backups() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListBackupsRequest() + +@pytest.mark.asyncio +async def test_list_backups_async(transport: str = 'grpc_asyncio', request_type=metastore.ListBackupsRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListBackupsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListBackupsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_backups_async_from_dict(): + await test_list_backups_async(request_type=dict) + + +def test_list_backups_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ListBackupsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), + '__call__') as call: + call.return_value = metastore.ListBackupsResponse() + client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backups_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ListBackupsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListBackupsResponse()) + await client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backups_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListBackupsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_backups( + 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_backups_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_backups( + metastore.ListBackupsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_backups_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListBackupsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListBackupsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_backups( + 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_backups_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_backups( + metastore.ListBackupsRequest(), + parent='parent_value', + ) + + +def test_list_backups_pager(transport_name: str = "grpc"): + client = DataprocMetastoreClient( + 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_backups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + metastore.Backup(), + ], + next_page_token='abc', + ), + metastore.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + ], + next_page_token='ghi', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_backups(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore.Backup) + for i in results) +def test_list_backups_pages(transport_name: str = "grpc"): + client = DataprocMetastoreClient( + 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_backups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + metastore.Backup(), + ], + next_page_token='abc', + ), + metastore.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + ], + next_page_token='ghi', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + ], + ), + RuntimeError, + ) + pages = list(client.list_backups(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_backups_async_pager(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + metastore.Backup(), + ], + next_page_token='abc', + ), + metastore.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + ], + next_page_token='ghi', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_backups(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, metastore.Backup) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_backups_async_pages(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + metastore.Backup(), + ], + next_page_token='abc', + ), + metastore.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + ], + next_page_token='ghi', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_backups(request={})).pages: # pragma: no branch + 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", [ + metastore.GetBackupRequest, + dict, +]) +def test_get_backup(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.Backup( + name='name_value', + state=metastore.Backup.State.CREATING, + description='description_value', + restoring_services=['restoring_services_value'], + ) + response = client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.Backup) + assert response.name == 'name_value' + assert response.state == metastore.Backup.State.CREATING + assert response.description == 'description_value' + assert response.restoring_services == ['restoring_services_value'] + + +def test_get_backup_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_backup), + '__call__') as call: + client.get_backup() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetBackupRequest() + +@pytest.mark.asyncio +async def test_get_backup_async(transport: str = 'grpc_asyncio', request_type=metastore.GetBackupRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.Backup( + name='name_value', + state=metastore.Backup.State.CREATING, + description='description_value', + restoring_services=['restoring_services_value'], + )) + response = await client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.Backup) + assert response.name == 'name_value' + assert response.state == metastore.Backup.State.CREATING + assert response.description == 'description_value' + assert response.restoring_services == ['restoring_services_value'] + + +@pytest.mark.asyncio +async def test_get_backup_async_from_dict(): + await test_get_backup_async(request_type=dict) + + +def test_get_backup_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.GetBackupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup), + '__call__') as call: + call.return_value = metastore.Backup() + client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backup_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.GetBackupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.Backup()) + await client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backup_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.Backup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_backup( + 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_backup_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_backup( + metastore.GetBackupRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_backup_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.Backup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.Backup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_backup( + 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_backup_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_backup( + metastore.GetBackupRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.CreateBackupRequest, + dict, +]) +def test_create_backup(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_backup_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_backup), + '__call__') as call: + client.create_backup() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateBackupRequest() + +@pytest.mark.asyncio +async def test_create_backup_async(transport: str = 'grpc_asyncio', request_type=metastore.CreateBackupRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_backup_async_from_dict(): + await test_create_backup_async(request_type=dict) + + +def test_create_backup_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.CreateBackupRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backup_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.CreateBackupRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backup_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_backup( + parent='parent_value', + backup=metastore.Backup(name='name_value'), + backup_id='backup_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].backup + mock_val = metastore.Backup(name='name_value') + assert arg == mock_val + arg = args[0].backup_id + mock_val = 'backup_id_value' + assert arg == mock_val + + +def test_create_backup_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_backup( + metastore.CreateBackupRequest(), + parent='parent_value', + backup=metastore.Backup(name='name_value'), + backup_id='backup_id_value', + ) + +@pytest.mark.asyncio +async def test_create_backup_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_backup( + parent='parent_value', + backup=metastore.Backup(name='name_value'), + backup_id='backup_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].backup + mock_val = metastore.Backup(name='name_value') + assert arg == mock_val + arg = args[0].backup_id + mock_val = 'backup_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_backup_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_backup( + metastore.CreateBackupRequest(), + parent='parent_value', + backup=metastore.Backup(name='name_value'), + backup_id='backup_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.DeleteBackupRequest, + dict, +]) +def test_delete_backup(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.DeleteBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_backup_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_backup), + '__call__') as call: + client.delete_backup() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.DeleteBackupRequest() + +@pytest.mark.asyncio +async def test_delete_backup_async(transport: str = 'grpc_asyncio', request_type=metastore.DeleteBackupRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.DeleteBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_backup_async_from_dict(): + await test_delete_backup_async(request_type=dict) + + +def test_delete_backup_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.DeleteBackupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backup_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.DeleteBackupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backup_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_backup( + 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_backup_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_backup( + metastore.DeleteBackupRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_backup_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_backup( + 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_backup_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_backup( + metastore.DeleteBackupRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ListServicesRequest, + dict, +]) +def test_list_services_rest(request_type): + client = DataprocMetastoreClient( + 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 = metastore.ListServicesResponse( + 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 = metastore.ListServicesResponse.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_services(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_services_rest_required_fields(request_type=metastore.ListServicesRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_services._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_services._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.ListServicesResponse() + # 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 = metastore.ListServicesResponse.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_services(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_services_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_services._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_services_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_list_services") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_list_services") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.ListServicesRequest.pb(metastore.ListServicesRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.ListServicesResponse.to_json(metastore.ListServicesResponse()) + + request = metastore.ListServicesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.ListServicesResponse() + + client.list_services(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_services_rest_bad_request(transport: str = 'rest', request_type=metastore.ListServicesRequest): + client = DataprocMetastoreClient( + 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_services(request) + + +def test_list_services_rest_flattened(): + client = DataprocMetastoreClient( + 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 = metastore.ListServicesResponse() + + # 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 = metastore.ListServicesResponse.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_services(**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/*}/services" % client.transport._host, args[1]) + + +def test_list_services_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_services( + metastore.ListServicesRequest(), + parent='parent_value', + ) + + +def test_list_services_rest_pager(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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 = ( + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + metastore.Service(), + ], + next_page_token='abc', + ), + metastore.ListServicesResponse( + services=[], + next_page_token='def', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + ], + next_page_token='ghi', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(metastore.ListServicesResponse.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_services(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore.Service) + for i in results) + + pages = list(client.list_services(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", [ + metastore.GetServiceRequest, + dict, +]) +def test_get_service_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/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 = metastore.Service( + name='name_value', + network='network_value', + endpoint_uri='endpoint_uri_value', + port=453, + state=metastore.Service.State.CREATING, + state_message='state_message_value', + artifact_gcs_uri='artifact_gcs_uri_value', + tier=metastore.Service.Tier.DEVELOPER, + uid='uid_value', + release_channel=metastore.Service.ReleaseChannel.CANARY, + database_type=metastore.Service.DatabaseType.MYSQL, + hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value'), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = metastore.Service.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_service(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.Service) + assert response.name == 'name_value' + assert response.network == 'network_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.port == 453 + assert response.state == metastore.Service.State.CREATING + assert response.state_message == 'state_message_value' + assert response.artifact_gcs_uri == 'artifact_gcs_uri_value' + assert response.tier == metastore.Service.Tier.DEVELOPER + assert response.uid == 'uid_value' + assert response.release_channel == metastore.Service.ReleaseChannel.CANARY + assert response.database_type == metastore.Service.DatabaseType.MYSQL + + +def test_get_service_rest_required_fields(request_type=metastore.GetServiceRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_service._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_service._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.Service() + # 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 = metastore.Service.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_service(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_service_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_service_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_get_service") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_get_service") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.GetServiceRequest.pb(metastore.GetServiceRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.Service.to_json(metastore.Service()) + + request = metastore.GetServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.Service() + + client.get_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_service_rest_bad_request(transport: str = 'rest', request_type=metastore.GetServiceRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/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_service(request) + + +def test_get_service_rest_flattened(): + client = DataprocMetastoreClient( + 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 = metastore.Service() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/services/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 = metastore.Service.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_service(**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/*/services/*}" % client.transport._host, args[1]) + + +def test_get_service_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_service( + metastore.GetServiceRequest(), + name='name_value', + ) + + +def test_get_service_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.CreateServiceRequest, + dict, +]) +def test_create_service_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["service"] = {'hive_metastore_config': {'version': 'version_value', 'config_overrides': {}, 'kerberos_config': {'keytab': {'cloud_secret': 'cloud_secret_value'}, 'principal': 'principal_value', 'krb5_config_gcs_uri': 'krb5_config_gcs_uri_value'}}, 'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'network': 'network_value', 'endpoint_uri': 'endpoint_uri_value', 'port': 453, 'state': 1, 'state_message': 'state_message_value', 'artifact_gcs_uri': 'artifact_gcs_uri_value', 'tier': 1, 'maintenance_window': {'hour_of_day': {'value': 541}, 'day_of_week': 1}, 'uid': 'uid_value', 'metadata_management_activity': {'metadata_exports': [{'destination_gcs_uri': 'destination_gcs_uri_value', 'start_time': {}, 'end_time': {}, 'state': 1, 'database_dump_type': 1}], 'restores': [{'start_time': {}, 'end_time': {}, 'state': 1, 'backup': 'backup_value', 'type_': 1, 'details': 'details_value'}]}, 'release_channel': 1, 'encryption_config': {'kms_key': 'kms_key_value'}, 'network_config': {'consumers': [{'subnetwork': 'subnetwork_value', 'endpoint_uri': 'endpoint_uri_value'}]}, 'database_type': 1, 'telemetry_config': {'log_format': 1}} + request = request_type(**request_init) + + # Mock the http request call within the method and 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(name='operations/spam') + + # 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.create_service(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_service_rest_required_fields(request_type=metastore.CreateServiceRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["service_id"] = "" + 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 + assert "serviceId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "serviceId" in jsonified_request + assert jsonified_request["serviceId"] == request_init["service_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["serviceId"] = 'service_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_service._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", "service_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "serviceId" in jsonified_request + assert jsonified_request["serviceId"] == 'service_id_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_service(request) + + expected_params = [ + ( + "serviceId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_service_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "serviceId", )) & set(("parent", "serviceId", "service", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_service_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_create_service") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_create_service") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.CreateServiceRequest.pb(metastore.CreateServiceRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.CreateServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_service_rest_bad_request(transport: str = 'rest', request_type=metastore.CreateServiceRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["service"] = {'hive_metastore_config': {'version': 'version_value', 'config_overrides': {}, 'kerberos_config': {'keytab': {'cloud_secret': 'cloud_secret_value'}, 'principal': 'principal_value', 'krb5_config_gcs_uri': 'krb5_config_gcs_uri_value'}}, 'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'network': 'network_value', 'endpoint_uri': 'endpoint_uri_value', 'port': 453, 'state': 1, 'state_message': 'state_message_value', 'artifact_gcs_uri': 'artifact_gcs_uri_value', 'tier': 1, 'maintenance_window': {'hour_of_day': {'value': 541}, 'day_of_week': 1}, 'uid': 'uid_value', 'metadata_management_activity': {'metadata_exports': [{'destination_gcs_uri': 'destination_gcs_uri_value', 'start_time': {}, 'end_time': {}, 'state': 1, 'database_dump_type': 1}], 'restores': [{'start_time': {}, 'end_time': {}, 'state': 1, 'backup': 'backup_value', 'type_': 1, 'details': 'details_value'}]}, 'release_channel': 1, 'encryption_config': {'kms_key': 'kms_key_value'}, 'network_config': {'consumers': [{'subnetwork': 'subnetwork_value', 'endpoint_uri': 'endpoint_uri_value'}]}, 'database_type': 1, 'telemetry_config': {'log_format': 1}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_service(request) + + +def test_create_service_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # 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', + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + service_id='service_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_service(**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/*}/services" % client.transport._host, args[1]) + + +def test_create_service_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_service( + metastore.CreateServiceRequest(), + parent='parent_value', + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + service_id='service_id_value', + ) + + +def test_create_service_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.UpdateServiceRequest, + dict, +]) +def test_update_service_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service': {'name': 'projects/sample1/locations/sample2/services/sample3'}} + request_init["service"] = {'hive_metastore_config': {'version': 'version_value', 'config_overrides': {}, 'kerberos_config': {'keytab': {'cloud_secret': 'cloud_secret_value'}, 'principal': 'principal_value', 'krb5_config_gcs_uri': 'krb5_config_gcs_uri_value'}}, 'name': 'projects/sample1/locations/sample2/services/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'network': 'network_value', 'endpoint_uri': 'endpoint_uri_value', 'port': 453, 'state': 1, 'state_message': 'state_message_value', 'artifact_gcs_uri': 'artifact_gcs_uri_value', 'tier': 1, 'maintenance_window': {'hour_of_day': {'value': 541}, 'day_of_week': 1}, 'uid': 'uid_value', 'metadata_management_activity': {'metadata_exports': [{'destination_gcs_uri': 'destination_gcs_uri_value', 'start_time': {}, 'end_time': {}, 'state': 1, 'database_dump_type': 1}], 'restores': [{'start_time': {}, 'end_time': {}, 'state': 1, 'backup': 'backup_value', 'type_': 1, 'details': 'details_value'}]}, 'release_channel': 1, 'encryption_config': {'kms_key': 'kms_key_value'}, 'network_config': {'consumers': [{'subnetwork': 'subnetwork_value', 'endpoint_uri': 'endpoint_uri_value'}]}, 'database_type': 1, 'telemetry_config': {'log_format': 1}} + request = request_type(**request_init) + + # Mock the http request call within the method and 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(name='operations/spam') + + # 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.update_service(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_service_rest_required_fields(request_type=metastore.UpdateServiceRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_service._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_service._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_service(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_service_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "service", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_service_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_update_service") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_update_service") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.UpdateServiceRequest.pb(metastore.UpdateServiceRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.UpdateServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_service_rest_bad_request(transport: str = 'rest', request_type=metastore.UpdateServiceRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service': {'name': 'projects/sample1/locations/sample2/services/sample3'}} + request_init["service"] = {'hive_metastore_config': {'version': 'version_value', 'config_overrides': {}, 'kerberos_config': {'keytab': {'cloud_secret': 'cloud_secret_value'}, 'principal': 'principal_value', 'krb5_config_gcs_uri': 'krb5_config_gcs_uri_value'}}, 'name': 'projects/sample1/locations/sample2/services/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'network': 'network_value', 'endpoint_uri': 'endpoint_uri_value', 'port': 453, 'state': 1, 'state_message': 'state_message_value', 'artifact_gcs_uri': 'artifact_gcs_uri_value', 'tier': 1, 'maintenance_window': {'hour_of_day': {'value': 541}, 'day_of_week': 1}, 'uid': 'uid_value', 'metadata_management_activity': {'metadata_exports': [{'destination_gcs_uri': 'destination_gcs_uri_value', 'start_time': {}, 'end_time': {}, 'state': 1, 'database_dump_type': 1}], 'restores': [{'start_time': {}, 'end_time': {}, 'state': 1, 'backup': 'backup_value', 'type_': 1, 'details': 'details_value'}]}, 'release_channel': 1, 'encryption_config': {'kms_key': 'kms_key_value'}, 'network_config': {'consumers': [{'subnetwork': 'subnetwork_value', 'endpoint_uri': 'endpoint_uri_value'}]}, 'database_type': 1, 'telemetry_config': {'log_format': 1}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_service(request) + + +def test_update_service_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'service': {'name': 'projects/sample1/locations/sample2/services/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_service(**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/{service.name=projects/*/locations/*/services/*}" % client.transport._host, args[1]) + + +def test_update_service_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_service( + metastore.UpdateServiceRequest(), + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_service_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.DeleteServiceRequest, + dict, +]) +def test_delete_service_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/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(name='operations/spam') + + # 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.delete_service(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_service_rest_required_fields(request_type=metastore.DeleteServiceRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_service._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_service._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 "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # 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 = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_service(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_service_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_service_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_delete_service") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_delete_service") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.DeleteServiceRequest.pb(metastore.DeleteServiceRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.DeleteServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_service_rest_bad_request(transport: str = 'rest', request_type=metastore.DeleteServiceRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/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_service(request) + + +def test_delete_service_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/services/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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_service(**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/*/services/*}" % client.transport._host, args[1]) + + +def test_delete_service_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_service( + metastore.DeleteServiceRequest(), + name='name_value', + ) + + +def test_delete_service_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ListMetadataImportsRequest, + dict, +]) +def test_list_metadata_imports_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/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 = metastore.ListMetadataImportsResponse( + 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 = metastore.ListMetadataImportsResponse.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_metadata_imports(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMetadataImportsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_metadata_imports_rest_required_fields(request_type=metastore.ListMetadataImportsRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_metadata_imports._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_metadata_imports._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.ListMetadataImportsResponse() + # 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 = metastore.ListMetadataImportsResponse.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_metadata_imports(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_metadata_imports_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_metadata_imports._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_metadata_imports_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_list_metadata_imports") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_list_metadata_imports") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.ListMetadataImportsRequest.pb(metastore.ListMetadataImportsRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.ListMetadataImportsResponse.to_json(metastore.ListMetadataImportsResponse()) + + request = metastore.ListMetadataImportsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.ListMetadataImportsResponse() + + client.list_metadata_imports(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_metadata_imports_rest_bad_request(transport: str = 'rest', request_type=metastore.ListMetadataImportsRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/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_metadata_imports(request) + + +def test_list_metadata_imports_rest_flattened(): + client = DataprocMetastoreClient( + 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 = metastore.ListMetadataImportsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/services/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 = metastore.ListMetadataImportsResponse.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_metadata_imports(**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/*/services/*}/metadataImports" % client.transport._host, args[1]) + + +def test_list_metadata_imports_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_metadata_imports( + metastore.ListMetadataImportsRequest(), + parent='parent_value', + ) + + +def test_list_metadata_imports_rest_pager(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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 = ( + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + next_page_token='abc', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[], + next_page_token='def', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + ], + next_page_token='ghi', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(metastore.ListMetadataImportsResponse.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/services/sample3'} + + pager = client.list_metadata_imports(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore.MetadataImport) + for i in results) + + pages = list(client.list_metadata_imports(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", [ + metastore.GetMetadataImportRequest, + dict, +]) +def test_get_metadata_import_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/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 = metastore.MetadataImport( + name='name_value', + description='description_value', + state=metastore.MetadataImport.State.RUNNING, + database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = metastore.MetadataImport.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_metadata_import(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.MetadataImport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == metastore.MetadataImport.State.RUNNING + + +def test_get_metadata_import_rest_required_fields(request_type=metastore.GetMetadataImportRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_metadata_import._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_metadata_import._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.MetadataImport() + # 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 = metastore.MetadataImport.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_metadata_import(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_metadata_import_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_metadata_import._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_metadata_import_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_get_metadata_import") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_get_metadata_import") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.GetMetadataImportRequest.pb(metastore.GetMetadataImportRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.MetadataImport.to_json(metastore.MetadataImport()) + + request = metastore.GetMetadataImportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.MetadataImport() + + client.get_metadata_import(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_metadata_import_rest_bad_request(transport: str = 'rest', request_type=metastore.GetMetadataImportRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/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_metadata_import(request) + + +def test_get_metadata_import_rest_flattened(): + client = DataprocMetastoreClient( + 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 = metastore.MetadataImport() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/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 = metastore.MetadataImport.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_metadata_import(**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/*/services/*/metadataImports/*}" % client.transport._host, args[1]) + + +def test_get_metadata_import_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_metadata_import( + metastore.GetMetadataImportRequest(), + name='name_value', + ) + + +def test_get_metadata_import_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.CreateMetadataImportRequest, + dict, +]) +def test_create_metadata_import_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/sample3'} + request_init["metadata_import"] = {'database_dump': {'database_type': 1, 'gcs_uri': 'gcs_uri_value', 'type_': 1}, 'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'end_time': {}, 'state': 1} + request = request_type(**request_init) + + # Mock the http request call within the method and 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(name='operations/spam') + + # 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.create_metadata_import(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_metadata_import_rest_required_fields(request_type=metastore.CreateMetadataImportRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["metadata_import_id"] = "" + 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 + assert "metadataImportId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_metadata_import._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "metadataImportId" in jsonified_request + assert jsonified_request["metadataImportId"] == request_init["metadata_import_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["metadataImportId"] = 'metadata_import_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_metadata_import._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("metadata_import_id", "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' + assert "metadataImportId" in jsonified_request + assert jsonified_request["metadataImportId"] == 'metadata_import_id_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_metadata_import(request) + + expected_params = [ + ( + "metadataImportId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_metadata_import_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_metadata_import._get_unset_required_fields({}) + assert set(unset_fields) == (set(("metadataImportId", "requestId", )) & set(("parent", "metadataImportId", "metadataImport", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_metadata_import_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_create_metadata_import") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_create_metadata_import") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.CreateMetadataImportRequest.pb(metastore.CreateMetadataImportRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.CreateMetadataImportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_metadata_import(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_metadata_import_rest_bad_request(transport: str = 'rest', request_type=metastore.CreateMetadataImportRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/sample3'} + request_init["metadata_import"] = {'database_dump': {'database_type': 1, 'gcs_uri': 'gcs_uri_value', 'type_': 1}, 'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'end_time': {}, 'state': 1} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_metadata_import(request) + + +def test_create_metadata_import_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/services/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + metadata_import_id='metadata_import_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_metadata_import(**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/*/services/*}/metadataImports" % client.transport._host, args[1]) + + +def test_create_metadata_import_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_metadata_import( + metastore.CreateMetadataImportRequest(), + parent='parent_value', + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + metadata_import_id='metadata_import_id_value', + ) + + +def test_create_metadata_import_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.UpdateMetadataImportRequest, + dict, +]) +def test_update_metadata_import_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'metadata_import': {'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/sample4'}} + request_init["metadata_import"] = {'database_dump': {'database_type': 1, 'gcs_uri': 'gcs_uri_value', 'type_': 1}, 'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/sample4', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'end_time': {}, 'state': 1} + request = request_type(**request_init) + + # Mock the http request call within the method and 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(name='operations/spam') + + # 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.update_metadata_import(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_metadata_import_rest_required_fields(request_type=metastore.UpdateMetadataImportRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_metadata_import._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_metadata_import._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_metadata_import(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_metadata_import_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_metadata_import._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "metadataImport", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_metadata_import_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_update_metadata_import") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_update_metadata_import") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.UpdateMetadataImportRequest.pb(metastore.UpdateMetadataImportRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.UpdateMetadataImportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_metadata_import(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_metadata_import_rest_bad_request(transport: str = 'rest', request_type=metastore.UpdateMetadataImportRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'metadata_import': {'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/sample4'}} + request_init["metadata_import"] = {'database_dump': {'database_type': 1, 'gcs_uri': 'gcs_uri_value', 'type_': 1}, 'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/sample4', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'end_time': {}, 'state': 1} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_metadata_import(request) + + +def test_update_metadata_import_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'metadata_import': {'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + 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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_metadata_import(**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/{metadata_import.name=projects/*/locations/*/services/*/metadataImports/*}" % client.transport._host, args[1]) + + +def test_update_metadata_import_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_metadata_import( + metastore.UpdateMetadataImportRequest(), + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_metadata_import_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ExportMetadataRequest, + dict, +]) +def test_export_metadata_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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(name='operations/spam') + + # 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.export_metadata(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_export_metadata_rest_required_fields(request_type=metastore.ExportMetadataRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["service"] = "" + 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()).export_metadata._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["service"] = 'service_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_metadata._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "service" in jsonified_request + assert jsonified_request["service"] == 'service_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.export_metadata(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_export_metadata_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.export_metadata._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("service", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_metadata_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_export_metadata") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_export_metadata") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.ExportMetadataRequest.pb(metastore.ExportMetadataRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.ExportMetadataRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.export_metadata(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_export_metadata_rest_bad_request(transport: str = 'rest', request_type=metastore.ExportMetadataRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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.export_metadata(request) + + +def test_export_metadata_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.RestoreServiceRequest, + dict, +]) +def test_restore_service_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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(name='operations/spam') + + # 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.restore_service(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_restore_service_rest_required_fields(request_type=metastore.RestoreServiceRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["service"] = "" + request_init["backup"] = "" + 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()).restore_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["service"] = 'service_value' + jsonified_request["backup"] = 'backup_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).restore_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "service" in jsonified_request + assert jsonified_request["service"] == 'service_value' + assert "backup" in jsonified_request + assert jsonified_request["backup"] == 'backup_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.restore_service(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_restore_service_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.restore_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("service", "backup", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_restore_service_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_restore_service") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_restore_service") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.RestoreServiceRequest.pb(metastore.RestoreServiceRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.RestoreServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.restore_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_restore_service_rest_bad_request(transport: str = 'rest', request_type=metastore.RestoreServiceRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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.restore_service(request) + + +def test_restore_service_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'service': 'projects/sample1/locations/sample2/services/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + service='service_value', + backup='backup_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.restore_service(**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/{service=projects/*/locations/*/services/*}:restore" % client.transport._host, args[1]) + + +def test_restore_service_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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.restore_service( + metastore.RestoreServiceRequest(), + service='service_value', + backup='backup_value', + ) + + +def test_restore_service_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ListBackupsRequest, + dict, +]) +def test_list_backups_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/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 = metastore.ListBackupsResponse( + 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 = metastore.ListBackupsResponse.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_backups(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_backups_rest_required_fields(request_type=metastore.ListBackupsRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_backups._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_backups._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.ListBackupsResponse() + # 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 = metastore.ListBackupsResponse.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_backups(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_backups_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_backups._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_backups_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_list_backups") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_list_backups") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.ListBackupsRequest.pb(metastore.ListBackupsRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.ListBackupsResponse.to_json(metastore.ListBackupsResponse()) + + request = metastore.ListBackupsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.ListBackupsResponse() + + client.list_backups(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_backups_rest_bad_request(transport: str = 'rest', request_type=metastore.ListBackupsRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/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_backups(request) + + +def test_list_backups_rest_flattened(): + client = DataprocMetastoreClient( + 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 = metastore.ListBackupsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/services/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 = metastore.ListBackupsResponse.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_backups(**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/*/services/*}/backups" % client.transport._host, args[1]) + + +def test_list_backups_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_backups( + metastore.ListBackupsRequest(), + parent='parent_value', + ) + + +def test_list_backups_rest_pager(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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 = ( + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + metastore.Backup(), + ], + next_page_token='abc', + ), + metastore.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + ], + next_page_token='ghi', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(metastore.ListBackupsResponse.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/services/sample3'} + + pager = client.list_backups(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore.Backup) + for i in results) + + pages = list(client.list_backups(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", [ + metastore.GetBackupRequest, + dict, +]) +def test_get_backup_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/sample3/backups/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 = metastore.Backup( + name='name_value', + state=metastore.Backup.State.CREATING, + description='description_value', + restoring_services=['restoring_services_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = metastore.Backup.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_backup(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.Backup) + assert response.name == 'name_value' + assert response.state == metastore.Backup.State.CREATING + assert response.description == 'description_value' + assert response.restoring_services == ['restoring_services_value'] + + +def test_get_backup_rest_required_fields(request_type=metastore.GetBackupRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_backup._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_backup._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.Backup() + # 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 = metastore.Backup.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_backup(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_backup_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_backup_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_get_backup") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_get_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.GetBackupRequest.pb(metastore.GetBackupRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.Backup.to_json(metastore.Backup()) + + request = metastore.GetBackupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.Backup() + + client.get_backup(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_backup_rest_bad_request(transport: str = 'rest', request_type=metastore.GetBackupRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/sample3/backups/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_backup(request) + + +def test_get_backup_rest_flattened(): + client = DataprocMetastoreClient( + 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 = metastore.Backup() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/services/sample3/backups/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 = metastore.Backup.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_backup(**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/*/services/*/backups/*}" % client.transport._host, args[1]) + + +def test_get_backup_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_backup( + metastore.GetBackupRequest(), + name='name_value', + ) + + +def test_get_backup_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.CreateBackupRequest, + dict, +]) +def test_create_backup_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/sample3'} + request_init["backup"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}, 'state': 1, 'service_revision': {'hive_metastore_config': {'version': 'version_value', 'config_overrides': {}, 'kerberos_config': {'keytab': {'cloud_secret': 'cloud_secret_value'}, 'principal': 'principal_value', 'krb5_config_gcs_uri': 'krb5_config_gcs_uri_value'}}, 'name': 'name_value', 'create_time': {}, 'update_time': {}, 'labels': {}, 'network': 'network_value', 'endpoint_uri': 'endpoint_uri_value', 'port': 453, 'state': 1, 'state_message': 'state_message_value', 'artifact_gcs_uri': 'artifact_gcs_uri_value', 'tier': 1, 'maintenance_window': {'hour_of_day': {'value': 541}, 'day_of_week': 1}, 'uid': 'uid_value', 'metadata_management_activity': {'metadata_exports': [{'destination_gcs_uri': 'destination_gcs_uri_value', 'start_time': {}, 'end_time': {}, 'state': 1, 'database_dump_type': 1}], 'restores': [{'start_time': {}, 'end_time': {}, 'state': 1, 'backup': 'backup_value', 'type_': 1, 'details': 'details_value'}]}, 'release_channel': 1, 'encryption_config': {'kms_key': 'kms_key_value'}, 'network_config': {'consumers': [{'subnetwork': 'subnetwork_value', 'endpoint_uri': 'endpoint_uri_value'}]}, 'database_type': 1, 'telemetry_config': {'log_format': 1}}, 'description': 'description_value', 'restoring_services': ['restoring_services_value1', 'restoring_services_value2']} + request = request_type(**request_init) + + # Mock the http request call within the method and 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(name='operations/spam') + + # 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.create_backup(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_backup_rest_required_fields(request_type=metastore.CreateBackupRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["backup_id"] = "" + 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 + assert "backupId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_backup._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "backupId" in jsonified_request + assert jsonified_request["backupId"] == request_init["backup_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["backupId"] = 'backup_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_backup._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("backup_id", "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' + assert "backupId" in jsonified_request + assert jsonified_request["backupId"] == 'backup_id_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_backup(request) + + expected_params = [ + ( + "backupId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_backup_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(("backupId", "requestId", )) & set(("parent", "backupId", "backup", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_backup_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_create_backup") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_create_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.CreateBackupRequest.pb(metastore.CreateBackupRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.CreateBackupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_backup(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_backup_rest_bad_request(transport: str = 'rest', request_type=metastore.CreateBackupRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/sample3'} + request_init["backup"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}, 'state': 1, 'service_revision': {'hive_metastore_config': {'version': 'version_value', 'config_overrides': {}, 'kerberos_config': {'keytab': {'cloud_secret': 'cloud_secret_value'}, 'principal': 'principal_value', 'krb5_config_gcs_uri': 'krb5_config_gcs_uri_value'}}, 'name': 'name_value', 'create_time': {}, 'update_time': {}, 'labels': {}, 'network': 'network_value', 'endpoint_uri': 'endpoint_uri_value', 'port': 453, 'state': 1, 'state_message': 'state_message_value', 'artifact_gcs_uri': 'artifact_gcs_uri_value', 'tier': 1, 'maintenance_window': {'hour_of_day': {'value': 541}, 'day_of_week': 1}, 'uid': 'uid_value', 'metadata_management_activity': {'metadata_exports': [{'destination_gcs_uri': 'destination_gcs_uri_value', 'start_time': {}, 'end_time': {}, 'state': 1, 'database_dump_type': 1}], 'restores': [{'start_time': {}, 'end_time': {}, 'state': 1, 'backup': 'backup_value', 'type_': 1, 'details': 'details_value'}]}, 'release_channel': 1, 'encryption_config': {'kms_key': 'kms_key_value'}, 'network_config': {'consumers': [{'subnetwork': 'subnetwork_value', 'endpoint_uri': 'endpoint_uri_value'}]}, 'database_type': 1, 'telemetry_config': {'log_format': 1}}, 'description': 'description_value', 'restoring_services': ['restoring_services_value1', 'restoring_services_value2']} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_backup(request) + + +def test_create_backup_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/services/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + backup=metastore.Backup(name='name_value'), + backup_id='backup_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_backup(**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/*/services/*}/backups" % client.transport._host, args[1]) + + +def test_create_backup_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_backup( + metastore.CreateBackupRequest(), + parent='parent_value', + backup=metastore.Backup(name='name_value'), + backup_id='backup_id_value', + ) + + +def test_create_backup_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.DeleteBackupRequest, + dict, +]) +def test_delete_backup_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/sample3/backups/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 = operations_pb2.Operation(name='operations/spam') + + # 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.delete_backup(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_backup_rest_required_fields(request_type=metastore.DeleteBackupRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_backup._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_backup._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 "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # 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 = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_backup(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_backup_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_backup_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_delete_backup") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_delete_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.DeleteBackupRequest.pb(metastore.DeleteBackupRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.DeleteBackupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_backup(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_backup_rest_bad_request(transport: str = 'rest', request_type=metastore.DeleteBackupRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/sample3/backups/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.delete_backup(request) + + +def test_delete_backup_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/services/sample3/backups/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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_backup(**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/*/services/*/backups/*}" % client.transport._host, args[1]) + + +def test_delete_backup_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_backup( + metastore.DeleteBackupRequest(), + name='name_value', + ) + + +def test_delete_backup_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DataprocMetastoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DataprocMetastoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataprocMetastoreClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DataprocMetastoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DataprocMetastoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataprocMetastoreClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataprocMetastoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DataprocMetastoreClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataprocMetastoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DataprocMetastoreGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DataprocMetastoreGrpcTransport, + transports.DataprocMetastoreGrpcAsyncIOTransport, + transports.DataprocMetastoreRestTransport, +]) +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 = DataprocMetastoreClient.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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DataprocMetastoreGrpcTransport, + ) + +def test_dataproc_metastore_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DataprocMetastoreTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_dataproc_metastore_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.metastore_v1.services.dataproc_metastore.transports.DataprocMetastoreTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DataprocMetastoreTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_services', + 'get_service', + 'create_service', + 'update_service', + 'delete_service', + 'list_metadata_imports', + 'get_metadata_import', + 'create_metadata_import', + 'update_metadata_import', + 'export_metadata', + 'restore_service', + 'list_backups', + 'get_backup', + 'create_backup', + 'delete_backup', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_dataproc_metastore_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.metastore_v1.services.dataproc_metastore.transports.DataprocMetastoreTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataprocMetastoreTransport( + 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_dataproc_metastore_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.metastore_v1.services.dataproc_metastore.transports.DataprocMetastoreTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataprocMetastoreTransport() + adc.assert_called_once() + + +def test_dataproc_metastore_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) + DataprocMetastoreClient() + 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.DataprocMetastoreGrpcTransport, + transports.DataprocMetastoreGrpcAsyncIOTransport, + ], +) +def test_dataproc_metastore_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.DataprocMetastoreGrpcTransport, + transports.DataprocMetastoreGrpcAsyncIOTransport, + transports.DataprocMetastoreRestTransport, + ], +) +def test_dataproc_metastore_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.DataprocMetastoreGrpcTransport, grpc_helpers), + (transports.DataprocMetastoreGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_dataproc_metastore_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( + "metastore.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="metastore.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DataprocMetastoreGrpcTransport, transports.DataprocMetastoreGrpcAsyncIOTransport]) +def test_dataproc_metastore_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_dataproc_metastore_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.DataprocMetastoreRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_dataproc_metastore_rest_lro_client(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_dataproc_metastore_host_no_port(transport_name): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='metastore.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'metastore.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://metastore.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_dataproc_metastore_host_with_port(transport_name): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='metastore.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'metastore.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://metastore.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_dataproc_metastore_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DataprocMetastoreClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DataprocMetastoreClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_services._session + session2 = client2.transport.list_services._session + assert session1 != session2 + session1 = client1.transport.get_service._session + session2 = client2.transport.get_service._session + assert session1 != session2 + session1 = client1.transport.create_service._session + session2 = client2.transport.create_service._session + assert session1 != session2 + session1 = client1.transport.update_service._session + session2 = client2.transport.update_service._session + assert session1 != session2 + session1 = client1.transport.delete_service._session + session2 = client2.transport.delete_service._session + assert session1 != session2 + session1 = client1.transport.list_metadata_imports._session + session2 = client2.transport.list_metadata_imports._session + assert session1 != session2 + session1 = client1.transport.get_metadata_import._session + session2 = client2.transport.get_metadata_import._session + assert session1 != session2 + session1 = client1.transport.create_metadata_import._session + session2 = client2.transport.create_metadata_import._session + assert session1 != session2 + session1 = client1.transport.update_metadata_import._session + session2 = client2.transport.update_metadata_import._session + assert session1 != session2 + session1 = client1.transport.export_metadata._session + session2 = client2.transport.export_metadata._session + assert session1 != session2 + session1 = client1.transport.restore_service._session + session2 = client2.transport.restore_service._session + assert session1 != session2 + session1 = client1.transport.list_backups._session + session2 = client2.transport.list_backups._session + assert session1 != session2 + session1 = client1.transport.get_backup._session + session2 = client2.transport.get_backup._session + assert session1 != session2 + session1 = client1.transport.create_backup._session + session2 = client2.transport.create_backup._session + assert session1 != session2 + session1 = client1.transport.delete_backup._session + session2 = client2.transport.delete_backup._session + assert session1 != session2 +def test_dataproc_metastore_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataprocMetastoreGrpcTransport( + 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_dataproc_metastore_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataprocMetastoreGrpcAsyncIOTransport( + 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.DataprocMetastoreGrpcTransport, transports.DataprocMetastoreGrpcAsyncIOTransport]) +def test_dataproc_metastore_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.DataprocMetastoreGrpcTransport, transports.DataprocMetastoreGrpcAsyncIOTransport]) +def test_dataproc_metastore_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_dataproc_metastore_grpc_lro_client(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_dataproc_metastore_grpc_lro_async_client(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_backup_path(): + project = "squid" + location = "clam" + service = "whelk" + backup = "octopus" + expected = "projects/{project}/locations/{location}/services/{service}/backups/{backup}".format(project=project, location=location, service=service, backup=backup, ) + actual = DataprocMetastoreClient.backup_path(project, location, service, backup) + assert expected == actual + + +def test_parse_backup_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "service": "cuttlefish", + "backup": "mussel", + } + path = DataprocMetastoreClient.backup_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_backup_path(path) + assert expected == actual + +def test_metadata_import_path(): + project = "winkle" + location = "nautilus" + service = "scallop" + metadata_import = "abalone" + expected = "projects/{project}/locations/{location}/services/{service}/metadataImports/{metadata_import}".format(project=project, location=location, service=service, metadata_import=metadata_import, ) + actual = DataprocMetastoreClient.metadata_import_path(project, location, service, metadata_import) + assert expected == actual + + +def test_parse_metadata_import_path(): + expected = { + "project": "squid", + "location": "clam", + "service": "whelk", + "metadata_import": "octopus", + } + path = DataprocMetastoreClient.metadata_import_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_metadata_import_path(path) + assert expected == actual + +def test_network_path(): + project = "oyster" + network = "nudibranch" + expected = "projects/{project}/global/networks/{network}".format(project=project, network=network, ) + actual = DataprocMetastoreClient.network_path(project, network) + assert expected == actual + + +def test_parse_network_path(): + expected = { + "project": "cuttlefish", + "network": "mussel", + } + path = DataprocMetastoreClient.network_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_network_path(path) + assert expected == actual + +def test_service_path(): + project = "winkle" + location = "nautilus" + service = "scallop" + expected = "projects/{project}/locations/{location}/services/{service}".format(project=project, location=location, service=service, ) + actual = DataprocMetastoreClient.service_path(project, location, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "abalone", + "location": "squid", + "service": "clam", + } + path = DataprocMetastoreClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_service_path(path) + assert expected == actual + +def test_subnetwork_path(): + project = "whelk" + region = "octopus" + subnetwork = "oyster" + expected = "projects/{project}/regions/{region}/subnetworks/{subnetwork}".format(project=project, region=region, subnetwork=subnetwork, ) + actual = DataprocMetastoreClient.subnetwork_path(project, region, subnetwork) + assert expected == actual + + +def test_parse_subnetwork_path(): + expected = { + "project": "nudibranch", + "region": "cuttlefish", + "subnetwork": "mussel", + } + path = DataprocMetastoreClient.subnetwork_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_subnetwork_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DataprocMetastoreClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = DataprocMetastoreClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = DataprocMetastoreClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = DataprocMetastoreClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DataprocMetastoreClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = DataprocMetastoreClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = DataprocMetastoreClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = DataprocMetastoreClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = DataprocMetastoreClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = DataprocMetastoreClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.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.DataprocMetastoreTransport, '_prep_wrapped_messages') as prep: + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DataprocMetastoreTransport, '_prep_wrapped_messages') as prep: + transport_class = DataprocMetastoreClient.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 = DataprocMetastoreAsyncClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/services/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_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/services/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 = policy_pb2.Policy() + + # 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_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/services/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.set_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/services/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 = policy_pb2.Policy() + + # 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.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/services/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.test_iam_permissions(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/services/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 = iam_policy_pb2.TestIamPermissionsResponse() + + # 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.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreAsyncClient( + 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_get_operation(transport: str = "grpc"): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreAsyncClient( + 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreAsyncClient( + 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreAsyncClient( + 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreAsyncClient( + 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_set_iam_policy(transport: str = "grpc"): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the 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, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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", [ + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v1/tests/unit/gapic/metastore_v1/test_dataproc_metastore_federation.py b/owl-bot-staging/v1/tests/unit/gapic/metastore_v1/test_dataproc_metastore_federation.py new file mode 100644 index 0000000..7d74885 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/metastore_v1/test_dataproc_metastore_federation.py @@ -0,0 +1,5435 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.metastore_v1.services.dataproc_metastore_federation import DataprocMetastoreFederationAsyncClient +from google.cloud.metastore_v1.services.dataproc_metastore_federation import DataprocMetastoreFederationClient +from google.cloud.metastore_v1.services.dataproc_metastore_federation import pagers +from google.cloud.metastore_v1.services.dataproc_metastore_federation import transports +from google.cloud.metastore_v1.types import metastore +from google.cloud.metastore_v1.types import metastore_federation +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DataprocMetastoreFederationClient._get_default_mtls_endpoint(None) is None + assert DataprocMetastoreFederationClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DataprocMetastoreFederationClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DataprocMetastoreFederationClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DataprocMetastoreFederationClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DataprocMetastoreFederationClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DataprocMetastoreFederationClient, "grpc"), + (DataprocMetastoreFederationAsyncClient, "grpc_asyncio"), + (DataprocMetastoreFederationClient, "rest"), +]) +def test_dataproc_metastore_federation_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 == ( + 'metastore.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://metastore.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DataprocMetastoreFederationGrpcTransport, "grpc"), + (transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DataprocMetastoreFederationRestTransport, "rest"), +]) +def test_dataproc_metastore_federation_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", [ + (DataprocMetastoreFederationClient, "grpc"), + (DataprocMetastoreFederationAsyncClient, "grpc_asyncio"), + (DataprocMetastoreFederationClient, "rest"), +]) +def test_dataproc_metastore_federation_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 == ( + 'metastore.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://metastore.googleapis.com' + ) + + +def test_dataproc_metastore_federation_client_get_transport_class(): + transport = DataprocMetastoreFederationClient.get_transport_class() + available_transports = [ + transports.DataprocMetastoreFederationGrpcTransport, + transports.DataprocMetastoreFederationRestTransport, + ] + assert transport in available_transports + + transport = DataprocMetastoreFederationClient.get_transport_class("grpc") + assert transport == transports.DataprocMetastoreFederationGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport, "grpc"), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio"), + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationRestTransport, "rest"), +]) +@mock.patch.object(DataprocMetastoreFederationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreFederationClient)) +@mock.patch.object(DataprocMetastoreFederationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreFederationAsyncClient)) +def test_dataproc_metastore_federation_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(DataprocMetastoreFederationClient, '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(DataprocMetastoreFederationClient, '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", [ + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport, "grpc", "true"), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport, "grpc", "false"), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationRestTransport, "rest", "true"), + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationRestTransport, "rest", "false"), +]) +@mock.patch.object(DataprocMetastoreFederationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreFederationClient)) +@mock.patch.object(DataprocMetastoreFederationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreFederationAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_dataproc_metastore_federation_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", [ + DataprocMetastoreFederationClient, DataprocMetastoreFederationAsyncClient +]) +@mock.patch.object(DataprocMetastoreFederationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreFederationClient)) +@mock.patch.object(DataprocMetastoreFederationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreFederationAsyncClient)) +def test_dataproc_metastore_federation_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", [ + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport, "grpc"), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio"), + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationRestTransport, "rest"), +]) +def test_dataproc_metastore_federation_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", [ + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport, "grpc", grpc_helpers), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationRestTransport, "rest", None), +]) +def test_dataproc_metastore_federation_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_dataproc_metastore_federation_client_client_options_from_dict(): + with mock.patch('google.cloud.metastore_v1.services.dataproc_metastore_federation.transports.DataprocMetastoreFederationGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DataprocMetastoreFederationClient( + 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", [ + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport, "grpc", grpc_helpers), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_dataproc_metastore_federation_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( + "metastore.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="metastore.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.ListFederationsRequest, + dict, +]) +def test_list_federations(request_type, transport: str = 'grpc'): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore_federation.ListFederationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_federations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.ListFederationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFederationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_federations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreFederationClient( + credentials=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_federations), + '__call__') as call: + client.list_federations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.ListFederationsRequest() + +@pytest.mark.asyncio +async def test_list_federations_async(transport: str = 'grpc_asyncio', request_type=metastore_federation.ListFederationsRequest): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore_federation.ListFederationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_federations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.ListFederationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFederationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_federations_async_from_dict(): + await test_list_federations_async(request_type=dict) + + +def test_list_federations_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.ListFederationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_federations), + '__call__') as call: + call.return_value = metastore_federation.ListFederationsResponse() + client.list_federations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federations_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.ListFederationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_federations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore_federation.ListFederationsResponse()) + await client.list_federations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federations_flattened(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_federations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore_federation.ListFederationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_federations( + 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_federations_flattened_error(): + client = DataprocMetastoreFederationClient( + credentials=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_federations( + metastore_federation.ListFederationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_federations_flattened_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_federations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore_federation.ListFederationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore_federation.ListFederationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_federations( + 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_federations_flattened_error_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_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_federations( + metastore_federation.ListFederationsRequest(), + parent='parent_value', + ) + + +def test_list_federations_pager(transport_name: str = "grpc"): + client = DataprocMetastoreFederationClient( + 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_federations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + next_page_token='abc', + ), + metastore_federation.ListFederationsResponse( + federations=[], + next_page_token='def', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + ], + next_page_token='ghi', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_federations(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore_federation.Federation) + for i in results) +def test_list_federations_pages(transport_name: str = "grpc"): + client = DataprocMetastoreFederationClient( + 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_federations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + next_page_token='abc', + ), + metastore_federation.ListFederationsResponse( + federations=[], + next_page_token='def', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + ], + next_page_token='ghi', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_federations(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_federations_async_pager(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_federations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + next_page_token='abc', + ), + metastore_federation.ListFederationsResponse( + federations=[], + next_page_token='def', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + ], + next_page_token='ghi', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_federations(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, metastore_federation.Federation) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_federations_async_pages(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_federations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + next_page_token='abc', + ), + metastore_federation.ListFederationsResponse( + federations=[], + next_page_token='def', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + ], + next_page_token='ghi', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_federations(request={})).pages: # pragma: no branch + 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", [ + metastore_federation.GetFederationRequest, + dict, +]) +def test_get_federation(request_type, transport: str = 'grpc'): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore_federation.Federation( + name='name_value', + version='version_value', + endpoint_uri='endpoint_uri_value', + state=metastore_federation.Federation.State.CREATING, + state_message='state_message_value', + uid='uid_value', + ) + response = client.get_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.GetFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore_federation.Federation) + assert response.name == 'name_value' + assert response.version == 'version_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.state == metastore_federation.Federation.State.CREATING + assert response.state_message == 'state_message_value' + assert response.uid == 'uid_value' + + +def test_get_federation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreFederationClient( + credentials=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_federation), + '__call__') as call: + client.get_federation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.GetFederationRequest() + +@pytest.mark.asyncio +async def test_get_federation_async(transport: str = 'grpc_asyncio', request_type=metastore_federation.GetFederationRequest): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore_federation.Federation( + name='name_value', + version='version_value', + endpoint_uri='endpoint_uri_value', + state=metastore_federation.Federation.State.CREATING, + state_message='state_message_value', + uid='uid_value', + )) + response = await client.get_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.GetFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore_federation.Federation) + assert response.name == 'name_value' + assert response.version == 'version_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.state == metastore_federation.Federation.State.CREATING + assert response.state_message == 'state_message_value' + assert response.uid == 'uid_value' + + +@pytest.mark.asyncio +async def test_get_federation_async_from_dict(): + await test_get_federation_async(request_type=dict) + + +def test_get_federation_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.GetFederationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_federation), + '__call__') as call: + call.return_value = metastore_federation.Federation() + client.get_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federation_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.GetFederationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_federation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore_federation.Federation()) + await client.get_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federation_flattened(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore_federation.Federation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_federation( + 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_federation_flattened_error(): + client = DataprocMetastoreFederationClient( + credentials=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_federation( + metastore_federation.GetFederationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_federation_flattened_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore_federation.Federation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore_federation.Federation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_federation( + 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_federation_flattened_error_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_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_federation( + metastore_federation.GetFederationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.CreateFederationRequest, + dict, +]) +def test_create_federation(request_type, transport: str = 'grpc'): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.CreateFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_federation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreFederationClient( + credentials=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_federation), + '__call__') as call: + client.create_federation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.CreateFederationRequest() + +@pytest.mark.asyncio +async def test_create_federation_async(transport: str = 'grpc_asyncio', request_type=metastore_federation.CreateFederationRequest): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.CreateFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_federation_async_from_dict(): + await test_create_federation_async(request_type=dict) + + +def test_create_federation_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.CreateFederationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_federation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federation_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.CreateFederationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_federation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federation_flattened(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_federation( + parent='parent_value', + federation=metastore_federation.Federation(name='name_value'), + federation_id='federation_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].federation + mock_val = metastore_federation.Federation(name='name_value') + assert arg == mock_val + arg = args[0].federation_id + mock_val = 'federation_id_value' + assert arg == mock_val + + +def test_create_federation_flattened_error(): + client = DataprocMetastoreFederationClient( + credentials=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_federation( + metastore_federation.CreateFederationRequest(), + parent='parent_value', + federation=metastore_federation.Federation(name='name_value'), + federation_id='federation_id_value', + ) + +@pytest.mark.asyncio +async def test_create_federation_flattened_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_federation( + parent='parent_value', + federation=metastore_federation.Federation(name='name_value'), + federation_id='federation_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].federation + mock_val = metastore_federation.Federation(name='name_value') + assert arg == mock_val + arg = args[0].federation_id + mock_val = 'federation_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_federation_flattened_error_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_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_federation( + metastore_federation.CreateFederationRequest(), + parent='parent_value', + federation=metastore_federation.Federation(name='name_value'), + federation_id='federation_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.UpdateFederationRequest, + dict, +]) +def test_update_federation(request_type, transport: str = 'grpc'): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.UpdateFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_federation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreFederationClient( + credentials=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_federation), + '__call__') as call: + client.update_federation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.UpdateFederationRequest() + +@pytest.mark.asyncio +async def test_update_federation_async(transport: str = 'grpc_asyncio', request_type=metastore_federation.UpdateFederationRequest): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.UpdateFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_federation_async_from_dict(): + await test_update_federation_async(request_type=dict) + + +def test_update_federation_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.UpdateFederationRequest() + + request.federation.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_federation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'federation.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_federation_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.UpdateFederationRequest() + + request.federation.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_federation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'federation.name=name_value', + ) in kw['metadata'] + + +def test_update_federation_flattened(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_federation( + federation=metastore_federation.Federation(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].federation + mock_val = metastore_federation.Federation(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_federation_flattened_error(): + client = DataprocMetastoreFederationClient( + credentials=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_federation( + metastore_federation.UpdateFederationRequest(), + federation=metastore_federation.Federation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_federation_flattened_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_federation( + federation=metastore_federation.Federation(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].federation + mock_val = metastore_federation.Federation(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_federation_flattened_error_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_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_federation( + metastore_federation.UpdateFederationRequest(), + federation=metastore_federation.Federation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.DeleteFederationRequest, + dict, +]) +def test_delete_federation(request_type, transport: str = 'grpc'): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.DeleteFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_federation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreFederationClient( + credentials=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_federation), + '__call__') as call: + client.delete_federation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.DeleteFederationRequest() + +@pytest.mark.asyncio +async def test_delete_federation_async(transport: str = 'grpc_asyncio', request_type=metastore_federation.DeleteFederationRequest): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.DeleteFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_federation_async_from_dict(): + await test_delete_federation_async(request_type=dict) + + +def test_delete_federation_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.DeleteFederationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_federation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federation_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.DeleteFederationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_federation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federation_flattened(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_federation( + 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_federation_flattened_error(): + client = DataprocMetastoreFederationClient( + credentials=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_federation( + metastore_federation.DeleteFederationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_federation_flattened_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_federation( + 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_federation_flattened_error_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_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_federation( + metastore_federation.DeleteFederationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.ListFederationsRequest, + dict, +]) +def test_list_federations_rest(request_type): + client = DataprocMetastoreFederationClient( + 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 = metastore_federation.ListFederationsResponse( + 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 = metastore_federation.ListFederationsResponse.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_federations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFederationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_federations_rest_required_fields(request_type=metastore_federation.ListFederationsRequest): + transport_class = transports.DataprocMetastoreFederationRestTransport + + 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_federations._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_federations._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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore_federation.ListFederationsResponse() + # 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 = metastore_federation.ListFederationsResponse.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_federations(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_federations_rest_unset_required_fields(): + transport = transports.DataprocMetastoreFederationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_federations._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_federations_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreFederationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreFederationRestInterceptor(), + ) + client = DataprocMetastoreFederationClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "post_list_federations") as post, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "pre_list_federations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore_federation.ListFederationsRequest.pb(metastore_federation.ListFederationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore_federation.ListFederationsResponse.to_json(metastore_federation.ListFederationsResponse()) + + request = metastore_federation.ListFederationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore_federation.ListFederationsResponse() + + client.list_federations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_federations_rest_bad_request(transport: str = 'rest', request_type=metastore_federation.ListFederationsRequest): + client = DataprocMetastoreFederationClient( + 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_federations(request) + + +def test_list_federations_rest_flattened(): + client = DataprocMetastoreFederationClient( + 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 = metastore_federation.ListFederationsResponse() + + # 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 = metastore_federation.ListFederationsResponse.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_federations(**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/*}/federations" % client.transport._host, args[1]) + + +def test_list_federations_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreFederationClient( + 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_federations( + metastore_federation.ListFederationsRequest(), + parent='parent_value', + ) + + +def test_list_federations_rest_pager(transport: str = 'rest'): + client = DataprocMetastoreFederationClient( + 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 = ( + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + next_page_token='abc', + ), + metastore_federation.ListFederationsResponse( + federations=[], + next_page_token='def', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + ], + next_page_token='ghi', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(metastore_federation.ListFederationsResponse.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_federations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore_federation.Federation) + for i in results) + + pages = list(client.list_federations(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", [ + metastore_federation.GetFederationRequest, + dict, +]) +def test_get_federation_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/federations/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 = metastore_federation.Federation( + name='name_value', + version='version_value', + endpoint_uri='endpoint_uri_value', + state=metastore_federation.Federation.State.CREATING, + state_message='state_message_value', + uid='uid_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = metastore_federation.Federation.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_federation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore_federation.Federation) + assert response.name == 'name_value' + assert response.version == 'version_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.state == metastore_federation.Federation.State.CREATING + assert response.state_message == 'state_message_value' + assert response.uid == 'uid_value' + + +def test_get_federation_rest_required_fields(request_type=metastore_federation.GetFederationRequest): + transport_class = transports.DataprocMetastoreFederationRestTransport + + 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_federation._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_federation._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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore_federation.Federation() + # 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 = metastore_federation.Federation.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_federation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_federation_rest_unset_required_fields(): + transport = transports.DataprocMetastoreFederationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_federation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_federation_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreFederationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreFederationRestInterceptor(), + ) + client = DataprocMetastoreFederationClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "post_get_federation") as post, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "pre_get_federation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore_federation.GetFederationRequest.pb(metastore_federation.GetFederationRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore_federation.Federation.to_json(metastore_federation.Federation()) + + request = metastore_federation.GetFederationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore_federation.Federation() + + client.get_federation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_federation_rest_bad_request(transport: str = 'rest', request_type=metastore_federation.GetFederationRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/federations/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_federation(request) + + +def test_get_federation_rest_flattened(): + client = DataprocMetastoreFederationClient( + 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 = metastore_federation.Federation() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/federations/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 = metastore_federation.Federation.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_federation(**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/*/federations/*}" % client.transport._host, args[1]) + + +def test_get_federation_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreFederationClient( + 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_federation( + metastore_federation.GetFederationRequest(), + name='name_value', + ) + + +def test_get_federation_rest_error(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.CreateFederationRequest, + dict, +]) +def test_create_federation_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["federation"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'version': 'version_value', 'backend_metastores': {}, 'endpoint_uri': 'endpoint_uri_value', 'state': 1, 'state_message': 'state_message_value', 'uid': 'uid_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 = operations_pb2.Operation(name='operations/spam') + + # 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.create_federation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_federation_rest_required_fields(request_type=metastore_federation.CreateFederationRequest): + transport_class = transports.DataprocMetastoreFederationRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["federation_id"] = "" + 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 + assert "federationId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_federation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "federationId" in jsonified_request + assert jsonified_request["federationId"] == request_init["federation_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["federationId"] = 'federation_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_federation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("federation_id", "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' + assert "federationId" in jsonified_request + assert jsonified_request["federationId"] == 'federation_id_value' + + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_federation(request) + + expected_params = [ + ( + "federationId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_federation_rest_unset_required_fields(): + transport = transports.DataprocMetastoreFederationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_federation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("federationId", "requestId", )) & set(("parent", "federationId", "federation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_federation_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreFederationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreFederationRestInterceptor(), + ) + client = DataprocMetastoreFederationClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "post_create_federation") as post, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "pre_create_federation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore_federation.CreateFederationRequest.pb(metastore_federation.CreateFederationRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore_federation.CreateFederationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_federation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_federation_rest_bad_request(transport: str = 'rest', request_type=metastore_federation.CreateFederationRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["federation"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'version': 'version_value', 'backend_metastores': {}, 'endpoint_uri': 'endpoint_uri_value', 'state': 1, 'state_message': 'state_message_value', 'uid': 'uid_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_federation(request) + + +def test_create_federation_rest_flattened(): + client = DataprocMetastoreFederationClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # 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', + federation=metastore_federation.Federation(name='name_value'), + federation_id='federation_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_federation(**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/*}/federations" % client.transport._host, args[1]) + + +def test_create_federation_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreFederationClient( + 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_federation( + metastore_federation.CreateFederationRequest(), + parent='parent_value', + federation=metastore_federation.Federation(name='name_value'), + federation_id='federation_id_value', + ) + + +def test_create_federation_rest_error(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.UpdateFederationRequest, + dict, +]) +def test_update_federation_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'federation': {'name': 'projects/sample1/locations/sample2/federations/sample3'}} + request_init["federation"] = {'name': 'projects/sample1/locations/sample2/federations/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'version': 'version_value', 'backend_metastores': {}, 'endpoint_uri': 'endpoint_uri_value', 'state': 1, 'state_message': 'state_message_value', 'uid': 'uid_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 = operations_pb2.Operation(name='operations/spam') + + # 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.update_federation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_federation_rest_required_fields(request_type=metastore_federation.UpdateFederationRequest): + transport_class = transports.DataprocMetastoreFederationRestTransport + + 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_federation._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_federation._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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_federation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_federation_rest_unset_required_fields(): + transport = transports.DataprocMetastoreFederationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_federation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "federation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_federation_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreFederationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreFederationRestInterceptor(), + ) + client = DataprocMetastoreFederationClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "post_update_federation") as post, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "pre_update_federation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore_federation.UpdateFederationRequest.pb(metastore_federation.UpdateFederationRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore_federation.UpdateFederationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_federation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_federation_rest_bad_request(transport: str = 'rest', request_type=metastore_federation.UpdateFederationRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'federation': {'name': 'projects/sample1/locations/sample2/federations/sample3'}} + request_init["federation"] = {'name': 'projects/sample1/locations/sample2/federations/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'version': 'version_value', 'backend_metastores': {}, 'endpoint_uri': 'endpoint_uri_value', 'state': 1, 'state_message': 'state_message_value', 'uid': 'uid_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_federation(request) + + +def test_update_federation_rest_flattened(): + client = DataprocMetastoreFederationClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'federation': {'name': 'projects/sample1/locations/sample2/federations/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + federation=metastore_federation.Federation(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_federation(**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/{federation.name=projects/*/locations/*/federations/*}" % client.transport._host, args[1]) + + +def test_update_federation_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreFederationClient( + 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_federation( + metastore_federation.UpdateFederationRequest(), + federation=metastore_federation.Federation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_federation_rest_error(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.DeleteFederationRequest, + dict, +]) +def test_delete_federation_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/federations/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(name='operations/spam') + + # 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.delete_federation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_federation_rest_required_fields(request_type=metastore_federation.DeleteFederationRequest): + transport_class = transports.DataprocMetastoreFederationRestTransport + + 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_federation._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_federation._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 "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # 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 = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_federation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_federation_rest_unset_required_fields(): + transport = transports.DataprocMetastoreFederationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_federation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_federation_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreFederationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreFederationRestInterceptor(), + ) + client = DataprocMetastoreFederationClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "post_delete_federation") as post, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "pre_delete_federation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore_federation.DeleteFederationRequest.pb(metastore_federation.DeleteFederationRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore_federation.DeleteFederationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_federation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_federation_rest_bad_request(transport: str = 'rest', request_type=metastore_federation.DeleteFederationRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/federations/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_federation(request) + + +def test_delete_federation_rest_flattened(): + client = DataprocMetastoreFederationClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/federations/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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_federation(**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/*/federations/*}" % client.transport._host, args[1]) + + +def test_delete_federation_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreFederationClient( + 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_federation( + metastore_federation.DeleteFederationRequest(), + name='name_value', + ) + + +def test_delete_federation_rest_error(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DataprocMetastoreFederationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DataprocMetastoreFederationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataprocMetastoreFederationClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DataprocMetastoreFederationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DataprocMetastoreFederationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataprocMetastoreFederationClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataprocMetastoreFederationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DataprocMetastoreFederationClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataprocMetastoreFederationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DataprocMetastoreFederationGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DataprocMetastoreFederationGrpcTransport, + transports.DataprocMetastoreFederationGrpcAsyncIOTransport, + transports.DataprocMetastoreFederationRestTransport, +]) +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 = DataprocMetastoreFederationClient.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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DataprocMetastoreFederationGrpcTransport, + ) + +def test_dataproc_metastore_federation_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DataprocMetastoreFederationTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_dataproc_metastore_federation_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.metastore_v1.services.dataproc_metastore_federation.transports.DataprocMetastoreFederationTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DataprocMetastoreFederationTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_federations', + 'get_federation', + 'create_federation', + 'update_federation', + 'delete_federation', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_dataproc_metastore_federation_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.metastore_v1.services.dataproc_metastore_federation.transports.DataprocMetastoreFederationTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataprocMetastoreFederationTransport( + 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_dataproc_metastore_federation_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.metastore_v1.services.dataproc_metastore_federation.transports.DataprocMetastoreFederationTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataprocMetastoreFederationTransport() + adc.assert_called_once() + + +def test_dataproc_metastore_federation_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) + DataprocMetastoreFederationClient() + 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.DataprocMetastoreFederationGrpcTransport, + transports.DataprocMetastoreFederationGrpcAsyncIOTransport, + ], +) +def test_dataproc_metastore_federation_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.DataprocMetastoreFederationGrpcTransport, + transports.DataprocMetastoreFederationGrpcAsyncIOTransport, + transports.DataprocMetastoreFederationRestTransport, + ], +) +def test_dataproc_metastore_federation_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.DataprocMetastoreFederationGrpcTransport, grpc_helpers), + (transports.DataprocMetastoreFederationGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_dataproc_metastore_federation_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( + "metastore.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="metastore.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DataprocMetastoreFederationGrpcTransport, transports.DataprocMetastoreFederationGrpcAsyncIOTransport]) +def test_dataproc_metastore_federation_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_dataproc_metastore_federation_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.DataprocMetastoreFederationRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_dataproc_metastore_federation_rest_lro_client(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_dataproc_metastore_federation_host_no_port(transport_name): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='metastore.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'metastore.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://metastore.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_dataproc_metastore_federation_host_with_port(transport_name): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='metastore.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'metastore.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://metastore.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_dataproc_metastore_federation_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DataprocMetastoreFederationClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DataprocMetastoreFederationClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_federations._session + session2 = client2.transport.list_federations._session + assert session1 != session2 + session1 = client1.transport.get_federation._session + session2 = client2.transport.get_federation._session + assert session1 != session2 + session1 = client1.transport.create_federation._session + session2 = client2.transport.create_federation._session + assert session1 != session2 + session1 = client1.transport.update_federation._session + session2 = client2.transport.update_federation._session + assert session1 != session2 + session1 = client1.transport.delete_federation._session + session2 = client2.transport.delete_federation._session + assert session1 != session2 +def test_dataproc_metastore_federation_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataprocMetastoreFederationGrpcTransport( + 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_dataproc_metastore_federation_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataprocMetastoreFederationGrpcAsyncIOTransport( + 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.DataprocMetastoreFederationGrpcTransport, transports.DataprocMetastoreFederationGrpcAsyncIOTransport]) +def test_dataproc_metastore_federation_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.DataprocMetastoreFederationGrpcTransport, transports.DataprocMetastoreFederationGrpcAsyncIOTransport]) +def test_dataproc_metastore_federation_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_dataproc_metastore_federation_grpc_lro_client(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_dataproc_metastore_federation_grpc_lro_async_client(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_federation_path(): + project = "squid" + location = "clam" + federation = "whelk" + expected = "projects/{project}/locations/{location}/federations/{federation}".format(project=project, location=location, federation=federation, ) + actual = DataprocMetastoreFederationClient.federation_path(project, location, federation) + assert expected == actual + + +def test_parse_federation_path(): + expected = { + "project": "octopus", + "location": "oyster", + "federation": "nudibranch", + } + path = DataprocMetastoreFederationClient.federation_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreFederationClient.parse_federation_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DataprocMetastoreFederationClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = DataprocMetastoreFederationClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreFederationClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = DataprocMetastoreFederationClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = DataprocMetastoreFederationClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreFederationClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DataprocMetastoreFederationClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = DataprocMetastoreFederationClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreFederationClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = DataprocMetastoreFederationClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = DataprocMetastoreFederationClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreFederationClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = DataprocMetastoreFederationClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = DataprocMetastoreFederationClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreFederationClient.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.DataprocMetastoreFederationTransport, '_prep_wrapped_messages') as prep: + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DataprocMetastoreFederationTransport, '_prep_wrapped_messages') as prep: + transport_class = DataprocMetastoreFederationClient.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 = DataprocMetastoreFederationAsyncClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/services/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_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/services/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 = policy_pb2.Policy() + + # 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_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/services/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.set_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/services/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 = policy_pb2.Policy() + + # 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.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/services/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.test_iam_permissions(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/services/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 = iam_policy_pb2.TestIamPermissionsResponse() + + # 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.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationAsyncClient( + 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_get_operation(transport: str = "grpc"): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationAsyncClient( + 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationAsyncClient( + 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationAsyncClient( + 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationAsyncClient( + 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_set_iam_policy(transport: str = "grpc"): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the 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, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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", [ + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v1alpha/.coveragerc b/owl-bot-staging/v1alpha/.coveragerc new file mode 100644 index 0000000..6409f0c --- /dev/null +++ b/owl-bot-staging/v1alpha/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/metastore/__init__.py + google/cloud/metastore/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/v1alpha/.flake8 b/owl-bot-staging/v1alpha/.flake8 new file mode 100644 index 0000000..29227d4 --- /dev/null +++ b/owl-bot-staging/v1alpha/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v1alpha/MANIFEST.in b/owl-bot-staging/v1alpha/MANIFEST.in new file mode 100644 index 0000000..aba5479 --- /dev/null +++ b/owl-bot-staging/v1alpha/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/metastore *.py +recursive-include google/cloud/metastore_v1alpha *.py diff --git a/owl-bot-staging/v1alpha/README.rst b/owl-bot-staging/v1alpha/README.rst new file mode 100644 index 0000000..f16e3c2 --- /dev/null +++ b/owl-bot-staging/v1alpha/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Metastore 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 Metastore API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1alpha/docs/conf.py b/owl-bot-staging/v1alpha/docs/conf.py new file mode 100644 index 0000000..74eaefd --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-dataproc-metastore 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-dataproc-metastore" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google 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-dataproc-metastore-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-dataproc-metastore.tex", + u"google-cloud-dataproc-metastore 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-dataproc-metastore", + u"Google Cloud Metastore 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-dataproc-metastore", + u"google-cloud-dataproc-metastore Documentation", + author, + "google-cloud-dataproc-metastore", + "GAPIC library for Google Cloud Metastore API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1alpha/docs/index.rst b/owl-bot-staging/v1alpha/docs/index.rst new file mode 100644 index 0000000..04518cf --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + metastore_v1alpha/services + metastore_v1alpha/types diff --git a/owl-bot-staging/v1alpha/docs/metastore_v1alpha/dataproc_metastore.rst b/owl-bot-staging/v1alpha/docs/metastore_v1alpha/dataproc_metastore.rst new file mode 100644 index 0000000..9806d0e --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/metastore_v1alpha/dataproc_metastore.rst @@ -0,0 +1,10 @@ +DataprocMetastore +----------------------------------- + +.. automodule:: google.cloud.metastore_v1alpha.services.dataproc_metastore + :members: + :inherited-members: + +.. automodule:: google.cloud.metastore_v1alpha.services.dataproc_metastore.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1alpha/docs/metastore_v1alpha/dataproc_metastore_federation.rst b/owl-bot-staging/v1alpha/docs/metastore_v1alpha/dataproc_metastore_federation.rst new file mode 100644 index 0000000..71b4b18 --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/metastore_v1alpha/dataproc_metastore_federation.rst @@ -0,0 +1,10 @@ +DataprocMetastoreFederation +--------------------------------------------- + +.. automodule:: google.cloud.metastore_v1alpha.services.dataproc_metastore_federation + :members: + :inherited-members: + +.. automodule:: google.cloud.metastore_v1alpha.services.dataproc_metastore_federation.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1alpha/docs/metastore_v1alpha/services.rst b/owl-bot-staging/v1alpha/docs/metastore_v1alpha/services.rst new file mode 100644 index 0000000..5e2f664 --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/metastore_v1alpha/services.rst @@ -0,0 +1,7 @@ +Services for Google Cloud Metastore v1alpha API +=============================================== +.. toctree:: + :maxdepth: 2 + + dataproc_metastore + dataproc_metastore_federation diff --git a/owl-bot-staging/v1alpha/docs/metastore_v1alpha/types.rst b/owl-bot-staging/v1alpha/docs/metastore_v1alpha/types.rst new file mode 100644 index 0000000..4713153 --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/metastore_v1alpha/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Metastore v1alpha API +============================================ + +.. automodule:: google.cloud.metastore_v1alpha.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore/__init__.py b/owl-bot-staging/v1alpha/google/cloud/metastore/__init__.py new file mode 100644 index 0000000..4c3cc31 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore/__init__.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.metastore import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.metastore_v1alpha.services.dataproc_metastore.client import DataprocMetastoreClient +from google.cloud.metastore_v1alpha.services.dataproc_metastore.async_client import DataprocMetastoreAsyncClient +from google.cloud.metastore_v1alpha.services.dataproc_metastore_federation.client import DataprocMetastoreFederationClient +from google.cloud.metastore_v1alpha.services.dataproc_metastore_federation.async_client import DataprocMetastoreFederationAsyncClient + +from google.cloud.metastore_v1alpha.types.metastore import AlterMetadataResourceLocationRequest +from google.cloud.metastore_v1alpha.types.metastore import AlterMetadataResourceLocationResponse +from google.cloud.metastore_v1alpha.types.metastore import AuxiliaryVersionConfig +from google.cloud.metastore_v1alpha.types.metastore import Backup +from google.cloud.metastore_v1alpha.types.metastore import CreateBackupRequest +from google.cloud.metastore_v1alpha.types.metastore import CreateMetadataImportRequest +from google.cloud.metastore_v1alpha.types.metastore import CreateServiceRequest +from google.cloud.metastore_v1alpha.types.metastore import DatabaseDumpSpec +from google.cloud.metastore_v1alpha.types.metastore import DataCatalogConfig +from google.cloud.metastore_v1alpha.types.metastore import DataplexConfig +from google.cloud.metastore_v1alpha.types.metastore import DeleteBackupRequest +from google.cloud.metastore_v1alpha.types.metastore import DeleteServiceRequest +from google.cloud.metastore_v1alpha.types.metastore import EncryptionConfig +from google.cloud.metastore_v1alpha.types.metastore import ExportMetadataRequest +from google.cloud.metastore_v1alpha.types.metastore import GetBackupRequest +from google.cloud.metastore_v1alpha.types.metastore import GetMetadataImportRequest +from google.cloud.metastore_v1alpha.types.metastore import GetServiceRequest +from google.cloud.metastore_v1alpha.types.metastore import HiveMetastoreConfig +from google.cloud.metastore_v1alpha.types.metastore import KerberosConfig +from google.cloud.metastore_v1alpha.types.metastore import Lake +from google.cloud.metastore_v1alpha.types.metastore import ListBackupsRequest +from google.cloud.metastore_v1alpha.types.metastore import ListBackupsResponse +from google.cloud.metastore_v1alpha.types.metastore import ListMetadataImportsRequest +from google.cloud.metastore_v1alpha.types.metastore import ListMetadataImportsResponse +from google.cloud.metastore_v1alpha.types.metastore import ListServicesRequest +from google.cloud.metastore_v1alpha.types.metastore import ListServicesResponse +from google.cloud.metastore_v1alpha.types.metastore import LocationMetadata +from google.cloud.metastore_v1alpha.types.metastore import MaintenanceWindow +from google.cloud.metastore_v1alpha.types.metastore import MetadataExport +from google.cloud.metastore_v1alpha.types.metastore import MetadataImport +from google.cloud.metastore_v1alpha.types.metastore import MetadataIntegration +from google.cloud.metastore_v1alpha.types.metastore import MetadataManagementActivity +from google.cloud.metastore_v1alpha.types.metastore import MoveTableToDatabaseRequest +from google.cloud.metastore_v1alpha.types.metastore import MoveTableToDatabaseResponse +from google.cloud.metastore_v1alpha.types.metastore import NetworkConfig +from google.cloud.metastore_v1alpha.types.metastore import OperationMetadata +from google.cloud.metastore_v1alpha.types.metastore import QueryMetadataRequest +from google.cloud.metastore_v1alpha.types.metastore import QueryMetadataResponse +from google.cloud.metastore_v1alpha.types.metastore import RemoveIamPolicyRequest +from google.cloud.metastore_v1alpha.types.metastore import RemoveIamPolicyResponse +from google.cloud.metastore_v1alpha.types.metastore import Restore +from google.cloud.metastore_v1alpha.types.metastore import RestoreServiceRequest +from google.cloud.metastore_v1alpha.types.metastore import Secret +from google.cloud.metastore_v1alpha.types.metastore import Service +from google.cloud.metastore_v1alpha.types.metastore import TelemetryConfig +from google.cloud.metastore_v1alpha.types.metastore import UpdateMetadataImportRequest +from google.cloud.metastore_v1alpha.types.metastore import UpdateServiceRequest +from google.cloud.metastore_v1alpha.types.metastore_federation import BackendMetastore +from google.cloud.metastore_v1alpha.types.metastore_federation import CreateFederationRequest +from google.cloud.metastore_v1alpha.types.metastore_federation import DeleteFederationRequest +from google.cloud.metastore_v1alpha.types.metastore_federation import Federation +from google.cloud.metastore_v1alpha.types.metastore_federation import GetFederationRequest +from google.cloud.metastore_v1alpha.types.metastore_federation import ListFederationsRequest +from google.cloud.metastore_v1alpha.types.metastore_federation import ListFederationsResponse +from google.cloud.metastore_v1alpha.types.metastore_federation import UpdateFederationRequest + +__all__ = ('DataprocMetastoreClient', + 'DataprocMetastoreAsyncClient', + 'DataprocMetastoreFederationClient', + 'DataprocMetastoreFederationAsyncClient', + 'AlterMetadataResourceLocationRequest', + 'AlterMetadataResourceLocationResponse', + 'AuxiliaryVersionConfig', + 'Backup', + 'CreateBackupRequest', + 'CreateMetadataImportRequest', + 'CreateServiceRequest', + 'DatabaseDumpSpec', + 'DataCatalogConfig', + 'DataplexConfig', + 'DeleteBackupRequest', + 'DeleteServiceRequest', + 'EncryptionConfig', + 'ExportMetadataRequest', + 'GetBackupRequest', + 'GetMetadataImportRequest', + 'GetServiceRequest', + 'HiveMetastoreConfig', + 'KerberosConfig', + 'Lake', + 'ListBackupsRequest', + 'ListBackupsResponse', + 'ListMetadataImportsRequest', + 'ListMetadataImportsResponse', + 'ListServicesRequest', + 'ListServicesResponse', + 'LocationMetadata', + 'MaintenanceWindow', + 'MetadataExport', + 'MetadataImport', + 'MetadataIntegration', + 'MetadataManagementActivity', + 'MoveTableToDatabaseRequest', + 'MoveTableToDatabaseResponse', + 'NetworkConfig', + 'OperationMetadata', + 'QueryMetadataRequest', + 'QueryMetadataResponse', + 'RemoveIamPolicyRequest', + 'RemoveIamPolicyResponse', + 'Restore', + 'RestoreServiceRequest', + 'Secret', + 'Service', + 'TelemetryConfig', + 'UpdateMetadataImportRequest', + 'UpdateServiceRequest', + 'BackendMetastore', + 'CreateFederationRequest', + 'DeleteFederationRequest', + 'Federation', + 'GetFederationRequest', + 'ListFederationsRequest', + 'ListFederationsResponse', + 'UpdateFederationRequest', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore/gapic_version.py b/owl-bot-staging/v1alpha/google/cloud/metastore/gapic_version.py new file mode 100644 index 0000000..405b1ce --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore/py.typed b/owl-bot-staging/v1alpha/google/cloud/metastore/py.typed new file mode 100644 index 0000000..f949c43 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-dataproc-metastore package uses inline types. diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/__init__.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/__init__.py new file mode 100644 index 0000000..b9c6349 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/__init__.py @@ -0,0 +1,142 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.metastore_v1alpha import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.dataproc_metastore import DataprocMetastoreClient +from .services.dataproc_metastore import DataprocMetastoreAsyncClient +from .services.dataproc_metastore_federation import DataprocMetastoreFederationClient +from .services.dataproc_metastore_federation import DataprocMetastoreFederationAsyncClient + +from .types.metastore import AlterMetadataResourceLocationRequest +from .types.metastore import AlterMetadataResourceLocationResponse +from .types.metastore import AuxiliaryVersionConfig +from .types.metastore import Backup +from .types.metastore import CreateBackupRequest +from .types.metastore import CreateMetadataImportRequest +from .types.metastore import CreateServiceRequest +from .types.metastore import DatabaseDumpSpec +from .types.metastore import DataCatalogConfig +from .types.metastore import DataplexConfig +from .types.metastore import DeleteBackupRequest +from .types.metastore import DeleteServiceRequest +from .types.metastore import EncryptionConfig +from .types.metastore import ExportMetadataRequest +from .types.metastore import GetBackupRequest +from .types.metastore import GetMetadataImportRequest +from .types.metastore import GetServiceRequest +from .types.metastore import HiveMetastoreConfig +from .types.metastore import KerberosConfig +from .types.metastore import Lake +from .types.metastore import ListBackupsRequest +from .types.metastore import ListBackupsResponse +from .types.metastore import ListMetadataImportsRequest +from .types.metastore import ListMetadataImportsResponse +from .types.metastore import ListServicesRequest +from .types.metastore import ListServicesResponse +from .types.metastore import LocationMetadata +from .types.metastore import MaintenanceWindow +from .types.metastore import MetadataExport +from .types.metastore import MetadataImport +from .types.metastore import MetadataIntegration +from .types.metastore import MetadataManagementActivity +from .types.metastore import MoveTableToDatabaseRequest +from .types.metastore import MoveTableToDatabaseResponse +from .types.metastore import NetworkConfig +from .types.metastore import OperationMetadata +from .types.metastore import QueryMetadataRequest +from .types.metastore import QueryMetadataResponse +from .types.metastore import RemoveIamPolicyRequest +from .types.metastore import RemoveIamPolicyResponse +from .types.metastore import Restore +from .types.metastore import RestoreServiceRequest +from .types.metastore import Secret +from .types.metastore import Service +from .types.metastore import TelemetryConfig +from .types.metastore import UpdateMetadataImportRequest +from .types.metastore import UpdateServiceRequest +from .types.metastore_federation import BackendMetastore +from .types.metastore_federation import CreateFederationRequest +from .types.metastore_federation import DeleteFederationRequest +from .types.metastore_federation import Federation +from .types.metastore_federation import GetFederationRequest +from .types.metastore_federation import ListFederationsRequest +from .types.metastore_federation import ListFederationsResponse +from .types.metastore_federation import UpdateFederationRequest + +__all__ = ( + 'DataprocMetastoreAsyncClient', + 'DataprocMetastoreFederationAsyncClient', +'AlterMetadataResourceLocationRequest', +'AlterMetadataResourceLocationResponse', +'AuxiliaryVersionConfig', +'BackendMetastore', +'Backup', +'CreateBackupRequest', +'CreateFederationRequest', +'CreateMetadataImportRequest', +'CreateServiceRequest', +'DataCatalogConfig', +'DatabaseDumpSpec', +'DataplexConfig', +'DataprocMetastoreClient', +'DataprocMetastoreFederationClient', +'DeleteBackupRequest', +'DeleteFederationRequest', +'DeleteServiceRequest', +'EncryptionConfig', +'ExportMetadataRequest', +'Federation', +'GetBackupRequest', +'GetFederationRequest', +'GetMetadataImportRequest', +'GetServiceRequest', +'HiveMetastoreConfig', +'KerberosConfig', +'Lake', +'ListBackupsRequest', +'ListBackupsResponse', +'ListFederationsRequest', +'ListFederationsResponse', +'ListMetadataImportsRequest', +'ListMetadataImportsResponse', +'ListServicesRequest', +'ListServicesResponse', +'LocationMetadata', +'MaintenanceWindow', +'MetadataExport', +'MetadataImport', +'MetadataIntegration', +'MetadataManagementActivity', +'MoveTableToDatabaseRequest', +'MoveTableToDatabaseResponse', +'NetworkConfig', +'OperationMetadata', +'QueryMetadataRequest', +'QueryMetadataResponse', +'RemoveIamPolicyRequest', +'RemoveIamPolicyResponse', +'Restore', +'RestoreServiceRequest', +'Secret', +'Service', +'TelemetryConfig', +'UpdateFederationRequest', +'UpdateMetadataImportRequest', +'UpdateServiceRequest', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/gapic_metadata.json b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/gapic_metadata.json new file mode 100644 index 0000000..30b9306 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/gapic_metadata.json @@ -0,0 +1,407 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.metastore_v1alpha", + "protoPackage": "google.cloud.metastore.v1alpha", + "schema": "1.0", + "services": { + "DataprocMetastore": { + "clients": { + "grpc": { + "libraryClient": "DataprocMetastoreClient", + "rpcs": { + "AlterMetadataResourceLocation": { + "methods": [ + "alter_metadata_resource_location" + ] + }, + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateMetadataImport": { + "methods": [ + "create_metadata_import" + ] + }, + "CreateService": { + "methods": [ + "create_service" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "ExportMetadata": { + "methods": [ + "export_metadata" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetMetadataImport": { + "methods": [ + "get_metadata_import" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListMetadataImports": { + "methods": [ + "list_metadata_imports" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "MoveTableToDatabase": { + "methods": [ + "move_table_to_database" + ] + }, + "QueryMetadata": { + "methods": [ + "query_metadata" + ] + }, + "RemoveIamPolicy": { + "methods": [ + "remove_iam_policy" + ] + }, + "RestoreService": { + "methods": [ + "restore_service" + ] + }, + "UpdateMetadataImport": { + "methods": [ + "update_metadata_import" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DataprocMetastoreAsyncClient", + "rpcs": { + "AlterMetadataResourceLocation": { + "methods": [ + "alter_metadata_resource_location" + ] + }, + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateMetadataImport": { + "methods": [ + "create_metadata_import" + ] + }, + "CreateService": { + "methods": [ + "create_service" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "ExportMetadata": { + "methods": [ + "export_metadata" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetMetadataImport": { + "methods": [ + "get_metadata_import" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListMetadataImports": { + "methods": [ + "list_metadata_imports" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "MoveTableToDatabase": { + "methods": [ + "move_table_to_database" + ] + }, + "QueryMetadata": { + "methods": [ + "query_metadata" + ] + }, + "RemoveIamPolicy": { + "methods": [ + "remove_iam_policy" + ] + }, + "RestoreService": { + "methods": [ + "restore_service" + ] + }, + "UpdateMetadataImport": { + "methods": [ + "update_metadata_import" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + }, + "rest": { + "libraryClient": "DataprocMetastoreClient", + "rpcs": { + "AlterMetadataResourceLocation": { + "methods": [ + "alter_metadata_resource_location" + ] + }, + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateMetadataImport": { + "methods": [ + "create_metadata_import" + ] + }, + "CreateService": { + "methods": [ + "create_service" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "ExportMetadata": { + "methods": [ + "export_metadata" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetMetadataImport": { + "methods": [ + "get_metadata_import" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListMetadataImports": { + "methods": [ + "list_metadata_imports" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "MoveTableToDatabase": { + "methods": [ + "move_table_to_database" + ] + }, + "QueryMetadata": { + "methods": [ + "query_metadata" + ] + }, + "RemoveIamPolicy": { + "methods": [ + "remove_iam_policy" + ] + }, + "RestoreService": { + "methods": [ + "restore_service" + ] + }, + "UpdateMetadataImport": { + "methods": [ + "update_metadata_import" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + } + } + }, + "DataprocMetastoreFederation": { + "clients": { + "grpc": { + "libraryClient": "DataprocMetastoreFederationClient", + "rpcs": { + "CreateFederation": { + "methods": [ + "create_federation" + ] + }, + "DeleteFederation": { + "methods": [ + "delete_federation" + ] + }, + "GetFederation": { + "methods": [ + "get_federation" + ] + }, + "ListFederations": { + "methods": [ + "list_federations" + ] + }, + "UpdateFederation": { + "methods": [ + "update_federation" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DataprocMetastoreFederationAsyncClient", + "rpcs": { + "CreateFederation": { + "methods": [ + "create_federation" + ] + }, + "DeleteFederation": { + "methods": [ + "delete_federation" + ] + }, + "GetFederation": { + "methods": [ + "get_federation" + ] + }, + "ListFederations": { + "methods": [ + "list_federations" + ] + }, + "UpdateFederation": { + "methods": [ + "update_federation" + ] + } + } + }, + "rest": { + "libraryClient": "DataprocMetastoreFederationClient", + "rpcs": { + "CreateFederation": { + "methods": [ + "create_federation" + ] + }, + "DeleteFederation": { + "methods": [ + "delete_federation" + ] + }, + "GetFederation": { + "methods": [ + "get_federation" + ] + }, + "ListFederations": { + "methods": [ + "list_federations" + ] + }, + "UpdateFederation": { + "methods": [ + "update_federation" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/gapic_version.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/gapic_version.py new file mode 100644 index 0000000..405b1ce --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/py.typed b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/py.typed new file mode 100644 index 0000000..f949c43 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-dataproc-metastore package uses inline types. diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/__init__.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/__init__.py new file mode 100644 index 0000000..e8e1c38 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/__init__.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/__init__.py new file mode 100644 index 0000000..fb93e40 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import DataprocMetastoreClient +from .async_client import DataprocMetastoreAsyncClient + +__all__ = ( + 'DataprocMetastoreClient', + 'DataprocMetastoreAsyncClient', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/async_client.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/async_client.py new file mode 100644 index 0000000..4476ab6 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/async_client.py @@ -0,0 +1,3004 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.metastore_v1alpha import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1alpha.services.dataproc_metastore import pagers +from google.cloud.metastore_v1alpha.types import metastore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DataprocMetastoreTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DataprocMetastoreGrpcAsyncIOTransport +from .client import DataprocMetastoreClient + + +class DataprocMetastoreAsyncClient: + """Configures and manages metastore services. Metastore services are + fully managed, highly available, autoscaled, autohealing, OSS-native + deployments of technical metadata management software. Each + metastore service exposes a network endpoint through which metadata + queries are served. Metadata queries can originate from a variety of + sources, including Apache Hive, Apache Presto, and Apache Spark. + + The Dataproc Metastore API defines the following resource model: + + - The service works with a collection of Google Cloud projects, + named: ``/projects/*`` + + - Each project has a collection of available locations, named: + ``/locations/*`` (a location must refer to a Google Cloud + ``region``) + + - Each location has a collection of services, named: + ``/services/*`` + + - Dataproc Metastore services are resources with names of the form: + + ``/projects/{project_number}/locations/{location_id}/services/{service_id}``. + """ + + _client: DataprocMetastoreClient + + DEFAULT_ENDPOINT = DataprocMetastoreClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DataprocMetastoreClient.DEFAULT_MTLS_ENDPOINT + + backup_path = staticmethod(DataprocMetastoreClient.backup_path) + parse_backup_path = staticmethod(DataprocMetastoreClient.parse_backup_path) + lake_path = staticmethod(DataprocMetastoreClient.lake_path) + parse_lake_path = staticmethod(DataprocMetastoreClient.parse_lake_path) + metadata_import_path = staticmethod(DataprocMetastoreClient.metadata_import_path) + parse_metadata_import_path = staticmethod(DataprocMetastoreClient.parse_metadata_import_path) + network_path = staticmethod(DataprocMetastoreClient.network_path) + parse_network_path = staticmethod(DataprocMetastoreClient.parse_network_path) + service_path = staticmethod(DataprocMetastoreClient.service_path) + parse_service_path = staticmethod(DataprocMetastoreClient.parse_service_path) + subnetwork_path = staticmethod(DataprocMetastoreClient.subnetwork_path) + parse_subnetwork_path = staticmethod(DataprocMetastoreClient.parse_subnetwork_path) + common_billing_account_path = staticmethod(DataprocMetastoreClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DataprocMetastoreClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DataprocMetastoreClient.common_folder_path) + parse_common_folder_path = staticmethod(DataprocMetastoreClient.parse_common_folder_path) + common_organization_path = staticmethod(DataprocMetastoreClient.common_organization_path) + parse_common_organization_path = staticmethod(DataprocMetastoreClient.parse_common_organization_path) + common_project_path = staticmethod(DataprocMetastoreClient.common_project_path) + parse_common_project_path = staticmethod(DataprocMetastoreClient.parse_common_project_path) + common_location_path = staticmethod(DataprocMetastoreClient.common_location_path) + parse_common_location_path = staticmethod(DataprocMetastoreClient.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: + DataprocMetastoreAsyncClient: The constructed client. + """ + return DataprocMetastoreClient.from_service_account_info.__func__(DataprocMetastoreAsyncClient, 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: + DataprocMetastoreAsyncClient: The constructed client. + """ + return DataprocMetastoreClient.from_service_account_file.__func__(DataprocMetastoreAsyncClient, 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 DataprocMetastoreClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DataprocMetastoreTransport: + """Returns the transport used by the client instance. + + Returns: + DataprocMetastoreTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DataprocMetastoreClient).get_transport_class, type(DataprocMetastoreClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DataprocMetastoreTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dataproc metastore 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, ~.DataprocMetastoreTransport]): 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 = DataprocMetastoreClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_services(self, + request: Optional[Union[metastore.ListServicesRequest, 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.ListServicesAsyncPager: + r"""Lists services in a 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 metastore_v1alpha + + async def sample_list_services(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ListServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.ListServicesRequest, dict]]): + The request object. Request message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1alpha.DataprocMetastore.ListServices]. + parent (:class:`str`): + Required. The relative resource name of the location of + metastore services to list, in the following form: + + ``projects/{project_number}/locations/{location_id}``. + + 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.metastore_v1alpha.services.dataproc_metastore.pagers.ListServicesAsyncPager: + Response message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1alpha.DataprocMetastore.ListServices]. + + 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 = metastore.ListServicesRequest(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_services, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListServicesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_service(self, + request: Optional[Union[metastore.GetServiceRequest, 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]] = (), + ) -> metastore.Service: + r"""Gets the details of a single service. + + .. 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 metastore_v1alpha + + async def sample_get_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.GetServiceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_service(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.GetServiceRequest, dict]]): + The request object. Request message for + [DataprocMetastore.GetService][google.cloud.metastore.v1alpha.DataprocMetastore.GetService]. + name (:class:`str`): + Required. The relative resource name of the metastore + service to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + 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.metastore_v1alpha.types.Service: + A managed metastore service that + serves metadata queries. + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 = metastore.GetServiceRequest(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_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_service(self, + request: Optional[Union[metastore.CreateServiceRequest, dict]] = None, + *, + parent: Optional[str] = None, + service: Optional[metastore.Service] = None, + service_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a metastore service in a 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 metastore_v1alpha + + async def sample_create_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.CreateServiceRequest( + parent="parent_value", + service_id="service_id_value", + ) + + # Make the request + operation = client.create_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.CreateServiceRequest, dict]]): + The request object. Request message for + [DataprocMetastore.CreateService][google.cloud.metastore.v1alpha.DataprocMetastore.CreateService]. + parent (:class:`str`): + Required. The relative resource name of the location in + which to create a metastore service, in the following + form: + + ``projects/{project_number}/locations/{location_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service (:class:`google.cloud.metastore_v1alpha.types.Service`): + Required. The Metastore service to create. The ``name`` + field is ignored. The ID of the created metastore + service must be provided in the request's ``service_id`` + field. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_id (:class:`str`): + Required. The ID of the metastore + service, which is used as the final + component of the metastore service's + name. + This value must be between 2 and 63 + characters long inclusive, begin with a + letter, end with a letter or number, and + consist of alpha-numeric ASCII + characters or hyphens. + + This corresponds to the ``service_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1alpha.types.Service` A + managed metastore service that serves metadata queries. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, service, service_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = metastore.CreateServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if service is not None: + request.service = service + if service_id is not None: + request.service_id = service_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_service, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.Service, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_service(self, + request: Optional[Union[metastore.UpdateServiceRequest, dict]] = None, + *, + service: Optional[metastore.Service] = 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single service. + + .. 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 metastore_v1alpha + + async def sample_update_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.UpdateServiceRequest( + ) + + # Make the request + operation = client.update_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.UpdateServiceRequest, dict]]): + The request object. Request message for + [DataprocMetastore.UpdateService][google.cloud.metastore.v1alpha.DataprocMetastore.UpdateService]. + service (:class:`google.cloud.metastore_v1alpha.types.Service`): + Required. The metastore service to update. The server + only merges fields in the service if they are specified + in ``update_mask``. + + The metastore service's ``name`` field is used to + identify the metastore service to be updated. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. A field mask used to specify the fields to be + overwritten in the metastore service resource by the + update. Fields specified in the ``update_mask`` are + relative to the resource (not to the full request). A + field is overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1alpha.types.Service` A + managed metastore service that serves metadata queries. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, 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 = metastore.UpdateServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if service is not None: + request.service = service + 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_service, + 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(( + ("service.name", request.service.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.Service, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_service(self, + request: Optional[Union[metastore.DeleteServiceRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single service. + + .. 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 metastore_v1alpha + + async def sample_delete_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.DeleteServiceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.DeleteServiceRequest, dict]]): + The request object. Request message for + [DataprocMetastore.DeleteService][google.cloud.metastore.v1alpha.DataprocMetastore.DeleteService]. + name (:class:`str`): + Required. The relative resource name of the metastore + service to delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 = metastore.DeleteServiceRequest(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_service, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_metadata_imports(self, + request: Optional[Union[metastore.ListMetadataImportsRequest, 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.ListMetadataImportsAsyncPager: + r"""Lists imports in a service. + + .. 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 metastore_v1alpha + + async def sample_list_metadata_imports(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ListMetadataImportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_metadata_imports(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.ListMetadataImportsRequest, dict]]): + The request object. Request message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1alpha.DataprocMetastore.ListMetadataImports]. + parent (:class:`str`): + Required. The relative resource name of the service + whose metadata imports to list, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports``. + + 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.metastore_v1alpha.services.dataproc_metastore.pagers.ListMetadataImportsAsyncPager: + Response message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1alpha.DataprocMetastore.ListMetadataImports]. + + 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 = metastore.ListMetadataImportsRequest(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_metadata_imports, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMetadataImportsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_metadata_import(self, + request: Optional[Union[metastore.GetMetadataImportRequest, 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]] = (), + ) -> metastore.MetadataImport: + r"""Gets details of a single import. + + .. 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 metastore_v1alpha + + async def sample_get_metadata_import(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.GetMetadataImportRequest( + name="name_value", + ) + + # Make the request + response = await client.get_metadata_import(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.GetMetadataImportRequest, dict]]): + The request object. Request message for + [DataprocMetastore.GetMetadataImport][google.cloud.metastore.v1alpha.DataprocMetastore.GetMetadataImport]. + name (:class:`str`): + Required. The relative resource name of the metadata + import to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports/{import_id}``. + + 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.metastore_v1alpha.types.MetadataImport: + A metastore resource that imports + 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 = metastore.GetMetadataImportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_metadata_import, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_metadata_import(self, + request: Optional[Union[metastore.CreateMetadataImportRequest, dict]] = None, + *, + parent: Optional[str] = None, + metadata_import: Optional[metastore.MetadataImport] = None, + metadata_import_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new MetadataImport 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 metastore_v1alpha + + async def sample_create_metadata_import(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.CreateMetadataImportRequest( + parent="parent_value", + metadata_import_id="metadata_import_id_value", + ) + + # Make the request + operation = client.create_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.CreateMetadataImportRequest, dict]]): + The request object. Request message for + [DataprocMetastore.CreateMetadataImport][google.cloud.metastore.v1alpha.DataprocMetastore.CreateMetadataImport]. + parent (:class:`str`): + Required. The relative resource name of the service in + which to create a metastore import, in the following + form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + metadata_import (:class:`google.cloud.metastore_v1alpha.types.MetadataImport`): + Required. The metadata import to create. The ``name`` + field is ignored. The ID of the created metadata import + must be provided in the request's ``metadata_import_id`` + field. + + This corresponds to the ``metadata_import`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + metadata_import_id (:class:`str`): + Required. The ID of the metadata + import, which is used as the final + component of the metadata import's name. + This value must be between 1 and 64 + characters long, begin with a letter, + end with a letter or number, and consist + of alpha-numeric ASCII characters or + hyphens. + + This corresponds to the ``metadata_import_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1alpha.types.MetadataImport` + A metastore resource that imports 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([parent, metadata_import, metadata_import_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = metastore.CreateMetadataImportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if metadata_import is not None: + request.metadata_import = metadata_import + if metadata_import_id is not None: + request.metadata_import_id = metadata_import_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_metadata_import, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.MetadataImport, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_metadata_import(self, + request: Optional[Union[metastore.UpdateMetadataImportRequest, dict]] = None, + *, + metadata_import: Optional[metastore.MetadataImport] = 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a single import. + Only the description field of MetadataImport is + supported to be updated. + + .. 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 metastore_v1alpha + + async def sample_update_metadata_import(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.UpdateMetadataImportRequest( + ) + + # Make the request + operation = client.update_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.UpdateMetadataImportRequest, dict]]): + The request object. Request message for + [DataprocMetastore.UpdateMetadataImport][google.cloud.metastore.v1alpha.DataprocMetastore.UpdateMetadataImport]. + metadata_import (:class:`google.cloud.metastore_v1alpha.types.MetadataImport`): + Required. The metadata import to update. The server only + merges fields in the import if they are specified in + ``update_mask``. + + The metadata import's ``name`` field is used to identify + the metastore import to be updated. + + This corresponds to the ``metadata_import`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. A field mask used to specify the fields to be + overwritten in the metadata import resource by the + update. Fields specified in the ``update_mask`` are + relative to the resource (not to the full request). A + field is overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1alpha.types.MetadataImport` + A metastore resource that imports 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([metadata_import, 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 = metastore.UpdateMetadataImportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if metadata_import is not None: + request.metadata_import = metadata_import + 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_metadata_import, + 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(( + ("metadata_import.name", request.metadata_import.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.MetadataImport, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def export_metadata(self, + request: Optional[Union[metastore.ExportMetadataRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports metadata from a service. + + .. 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 metastore_v1alpha + + async def sample_export_metadata(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ExportMetadataRequest( + destination_gcs_folder="destination_gcs_folder_value", + service="service_value", + ) + + # Make the request + operation = client.export_metadata(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.ExportMetadataRequest, dict]]): + The request object. Request message for + [DataprocMetastore.ExportMetadata][google.cloud.metastore.v1alpha.DataprocMetastore.ExportMetadata]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1alpha.types.MetadataExport` + The details of a metadata export operation. + + """ + # Create or coerce a protobuf request object. + request = metastore.ExportMetadataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_metadata, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service", request.service), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.MetadataExport, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def restore_service(self, + request: Optional[Union[metastore.RestoreServiceRequest, dict]] = None, + *, + service: Optional[str] = None, + backup: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Restores a service from a backup. + + .. 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 metastore_v1alpha + + async def sample_restore_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.RestoreServiceRequest( + service="service_value", + backup="backup_value", + ) + + # Make the request + operation = client.restore_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.RestoreServiceRequest, dict]]): + The request object. Request message for [DataprocMetastore.Restore][]. + service (:class:`str`): + Required. The relative resource name of the metastore + service to run restore, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup (:class:`str`): + Required. The relative resource name of the metastore + service backup to restore from, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1alpha.types.Restore` + The details of a metadata restore operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, backup]) + if request is 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 = metastore.RestoreServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if service is not None: + request.service = service + if backup is not None: + request.backup = backup + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.restore_service, + 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(( + ("service", request.service), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.Restore, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_backups(self, + request: Optional[Union[metastore.ListBackupsRequest, 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.ListBackupsAsyncPager: + r"""Lists backups in a service. + + .. 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 metastore_v1alpha + + async def sample_list_backups(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.ListBackupsRequest, dict]]): + The request object. Request message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1alpha.DataprocMetastore.ListBackups]. + parent (:class:`str`): + Required. The relative resource name of the service + whose backups to list, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups``. + + 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.metastore_v1alpha.services.dataproc_metastore.pagers.ListBackupsAsyncPager: + Response message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1alpha.DataprocMetastore.ListBackups]. + + 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 = metastore.ListBackupsRequest(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_backups, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListBackupsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_backup(self, + request: Optional[Union[metastore.GetBackupRequest, 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]] = (), + ) -> metastore.Backup: + r"""Gets details of a single backup. + + .. 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 metastore_v1alpha + + async def sample_get_backup(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.GetBackupRequest, dict]]): + The request object. Request message for + [DataprocMetastore.GetBackup][google.cloud.metastore.v1alpha.DataprocMetastore.GetBackup]. + name (:class:`str`): + Required. The relative resource name of the backup to + retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + + 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.metastore_v1alpha.types.Backup: + The details of a backup resource. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = metastore.GetBackupRequest(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_backup, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_backup(self, + request: Optional[Union[metastore.CreateBackupRequest, dict]] = None, + *, + parent: Optional[str] = None, + backup: Optional[metastore.Backup] = None, + backup_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new backup 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 metastore_v1alpha + + async def sample_create_backup(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + ) + + # Make the request + operation = client.create_backup(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.CreateBackupRequest, dict]]): + The request object. Request message for + [DataprocMetastore.CreateBackup][google.cloud.metastore.v1alpha.DataprocMetastore.CreateBackup]. + parent (:class:`str`): + Required. The relative resource name of the service in + which to create a backup of the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup (:class:`google.cloud.metastore_v1alpha.types.Backup`): + Required. The backup to create. The ``name`` field is + ignored. The ID of the created backup must be provided + in the request's ``backup_id`` field. + + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_id (:class:`str`): + Required. The ID of the backup, which + is used as the final component of the + backup's name. + This value must be between 1 and 64 + characters long, begin with a letter, + end with a letter or number, and consist + of alpha-numeric ASCII characters or + hyphens. + + This corresponds to the ``backup_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1alpha.types.Backup` The + details of a backup resource. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, backup, backup_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = metastore.CreateBackupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if backup is not None: + request.backup = backup + if backup_id is not None: + request.backup_id = backup_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_backup, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.Backup, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_backup(self, + request: Optional[Union[metastore.DeleteBackupRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single backup. + + .. 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 metastore_v1alpha + + async def sample_delete_backup(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.DeleteBackupRequest, dict]]): + The request object. Request message for + [DataprocMetastore.DeleteBackup][google.cloud.metastore.v1alpha.DataprocMetastore.DeleteBackup]. + name (:class:`str`): + Required. The relative resource name of the backup to + delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 = metastore.DeleteBackupRequest(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_backup, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def remove_iam_policy(self, + request: Optional[Union[metastore.RemoveIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> metastore.RemoveIamPolicyResponse: + r"""Removes the attached IAM policies for a resource + + .. 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 metastore_v1alpha + + async def sample_remove_iam_policy(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.RemoveIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.remove_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.RemoveIamPolicyRequest, dict]]): + The request object. Request message for + [DataprocMetastore.RemoveIamPolicy][google.cloud.metastore.v1alpha.DataprocMetastore.RemoveIamPolicy]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.metastore_v1alpha.types.RemoveIamPolicyResponse: + Response message for + [DataprocMetastore.RemoveIamPolicy][google.cloud.metastore.v1alpha.DataprocMetastore.RemoveIamPolicy]. + + """ + # Create or coerce a protobuf request object. + request = metastore.RemoveIamPolicyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_iam_policy, + 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(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def query_metadata(self, + request: Optional[Union[metastore.QueryMetadataRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Query DPMS metadata. + + .. 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 metastore_v1alpha + + async def sample_query_metadata(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.QueryMetadataRequest( + service="service_value", + query="query_value", + ) + + # Make the request + operation = client.query_metadata(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.QueryMetadataRequest, dict]]): + The request object. Request message for + [DataprocMetastore.QueryMetadata][google.cloud.metastore.v1alpha.DataprocMetastore.QueryMetadata]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.metastore_v1alpha.types.QueryMetadataResponse` Response message for + [DataprocMetastore.QueryMetadata][google.cloud.metastore.v1alpha.DataprocMetastore.QueryMetadata]. + + """ + # Create or coerce a protobuf request object. + request = metastore.QueryMetadataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.query_metadata, + 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(( + ("service", request.service), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.QueryMetadataResponse, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def move_table_to_database(self, + request: Optional[Union[metastore.MoveTableToDatabaseRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Move a table to another database. + + .. 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 metastore_v1alpha + + async def sample_move_table_to_database(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.MoveTableToDatabaseRequest( + service="service_value", + table_name="table_name_value", + db_name="db_name_value", + destination_db_name="destination_db_name_value", + ) + + # Make the request + operation = client.move_table_to_database(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.MoveTableToDatabaseRequest, dict]]): + The request object. Request message for + [DataprocMetastore.MoveTableToDatabase][google.cloud.metastore.v1alpha.DataprocMetastore.MoveTableToDatabase]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.metastore_v1alpha.types.MoveTableToDatabaseResponse` Response message for + [DataprocMetastore.MoveTableToDatabase][google.cloud.metastore.v1alpha.DataprocMetastore.MoveTableToDatabase]. + + """ + # Create or coerce a protobuf request object. + request = metastore.MoveTableToDatabaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.move_table_to_database, + 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(( + ("service", request.service), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.MoveTableToDatabaseResponse, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def alter_metadata_resource_location(self, + request: Optional[Union[metastore.AlterMetadataResourceLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Alter metadata resource location. The metadata + resource can be a database, table, or partition. This + functionality only updates the parent directory for the + respective metadata resource and does not transfer any + existing data to the new 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 metastore_v1alpha + + async def sample_alter_metadata_resource_location(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.AlterMetadataResourceLocationRequest( + service="service_value", + resource_name="resource_name_value", + location_uri="location_uri_value", + ) + + # Make the request + operation = client.alter_metadata_resource_location(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.AlterMetadataResourceLocationRequest, dict]]): + The request object. Request message for + [DataprocMetastore.AlterMetadataResourceLocation][google.cloud.metastore.v1alpha.DataprocMetastore.AlterMetadataResourceLocation]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.metastore_v1alpha.types.AlterMetadataResourceLocationResponse` Response message for + [DataprocMetastore.AlterMetadataResourceLocation][google.cloud.metastore.v1alpha.DataprocMetastore.AlterMetadataResourceLocation]. + + """ + # Create or coerce a protobuf request object. + request = metastore.AlterMetadataResourceLocationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.alter_metadata_resource_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(( + ("service", request.service), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.AlterMetadataResourceLocationResponse, + metadata_type=metastore.OperationMetadata, + ) + + # 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.set_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.GetIamPolicyRequest(**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_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.test_iam_permissions, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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): + 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__ = ( + "DataprocMetastoreAsyncClient", +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/client.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/client.py new file mode 100644 index 0000000..abe0e6d --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/client.py @@ -0,0 +1,3253 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.metastore_v1alpha import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1alpha.services.dataproc_metastore import pagers +from google.cloud.metastore_v1alpha.types import metastore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DataprocMetastoreTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DataprocMetastoreGrpcTransport +from .transports.grpc_asyncio import DataprocMetastoreGrpcAsyncIOTransport +from .transports.rest import DataprocMetastoreRestTransport + + +class DataprocMetastoreClientMeta(type): + """Metaclass for the DataprocMetastore 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[DataprocMetastoreTransport]] + _transport_registry["grpc"] = DataprocMetastoreGrpcTransport + _transport_registry["grpc_asyncio"] = DataprocMetastoreGrpcAsyncIOTransport + _transport_registry["rest"] = DataprocMetastoreRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[DataprocMetastoreTransport]: + """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 DataprocMetastoreClient(metaclass=DataprocMetastoreClientMeta): + """Configures and manages metastore services. Metastore services are + fully managed, highly available, autoscaled, autohealing, OSS-native + deployments of technical metadata management software. Each + metastore service exposes a network endpoint through which metadata + queries are served. Metadata queries can originate from a variety of + sources, including Apache Hive, Apache Presto, and Apache Spark. + + The Dataproc Metastore API defines the following resource model: + + - The service works with a collection of Google Cloud projects, + named: ``/projects/*`` + + - Each project has a collection of available locations, named: + ``/locations/*`` (a location must refer to a Google Cloud + ``region``) + + - Each location has a collection of services, named: + ``/services/*`` + + - Dataproc Metastore services are resources with names of the form: + + ``/projects/{project_number}/locations/{location_id}/services/{service_id}``. + """ + + @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 = "metastore.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: + DataprocMetastoreClient: 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: + DataprocMetastoreClient: 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) -> DataprocMetastoreTransport: + """Returns the transport used by the client instance. + + Returns: + DataprocMetastoreTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def backup_path(project: str,location: str,service: str,backup: str,) -> str: + """Returns a fully-qualified backup string.""" + return "projects/{project}/locations/{location}/services/{service}/backups/{backup}".format(project=project, location=location, service=service, backup=backup, ) + + @staticmethod + def parse_backup_path(path: str) -> Dict[str,str]: + """Parses a backup path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/services/(?P.+?)/backups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def lake_path(project: str,location: str,lake: str,) -> str: + """Returns a fully-qualified lake string.""" + return "projects/{project}/locations/{location}/lakes/{lake}".format(project=project, location=location, lake=lake, ) + + @staticmethod + def parse_lake_path(path: str) -> Dict[str,str]: + """Parses a lake path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/lakes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def metadata_import_path(project: str,location: str,service: str,metadata_import: str,) -> str: + """Returns a fully-qualified metadata_import string.""" + return "projects/{project}/locations/{location}/services/{service}/metadataImports/{metadata_import}".format(project=project, location=location, service=service, metadata_import=metadata_import, ) + + @staticmethod + def parse_metadata_import_path(path: str) -> Dict[str,str]: + """Parses a metadata_import path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/services/(?P.+?)/metadataImports/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def network_path(project: str,network: str,) -> str: + """Returns a fully-qualified network string.""" + return "projects/{project}/global/networks/{network}".format(project=project, network=network, ) + + @staticmethod + def parse_network_path(path: str) -> Dict[str,str]: + """Parses a network path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/global/networks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_path(project: str,location: str,service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/services/{service}".format(project=project, location=location, service=service, ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str,str]: + """Parses a service path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/services/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def subnetwork_path(project: str,region: str,subnetwork: str,) -> str: + """Returns a fully-qualified subnetwork string.""" + return "projects/{project}/regions/{region}/subnetworks/{subnetwork}".format(project=project, region=region, subnetwork=subnetwork, ) + + @staticmethod + def parse_subnetwork_path(path: str) -> Dict[str,str]: + """Parses a subnetwork path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/regions/(?P.+?)/subnetworks/(?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, DataprocMetastoreTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dataproc metastore 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, DataprocMetastoreTransport]): 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, DataprocMetastoreTransport): + # transport is a DataprocMetastoreTransport 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_services(self, + request: Optional[Union[metastore.ListServicesRequest, 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.ListServicesPager: + r"""Lists services in a 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 metastore_v1alpha + + def sample_list_services(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ListServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.ListServicesRequest, dict]): + The request object. Request message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1alpha.DataprocMetastore.ListServices]. + parent (str): + Required. The relative resource name of the location of + metastore services to list, in the following form: + + ``projects/{project_number}/locations/{location_id}``. + + 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.metastore_v1alpha.services.dataproc_metastore.pagers.ListServicesPager: + Response message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1alpha.DataprocMetastore.ListServices]. + + 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 metastore.ListServicesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.ListServicesRequest): + request = metastore.ListServicesRequest(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_services] + + # Certain 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.ListServicesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_service(self, + request: Optional[Union[metastore.GetServiceRequest, 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]] = (), + ) -> metastore.Service: + r"""Gets the details of a single service. + + .. 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 metastore_v1alpha + + def sample_get_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.GetServiceRequest( + name="name_value", + ) + + # Make the request + response = client.get_service(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.GetServiceRequest, dict]): + The request object. Request message for + [DataprocMetastore.GetService][google.cloud.metastore.v1alpha.DataprocMetastore.GetService]. + name (str): + Required. The relative resource name of the metastore + service to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + 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.metastore_v1alpha.types.Service: + A managed metastore service that + serves metadata queries. + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 metastore.GetServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.GetServiceRequest): + request = metastore.GetServiceRequest(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_service] + + # Certain 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_service(self, + request: Optional[Union[metastore.CreateServiceRequest, dict]] = None, + *, + parent: Optional[str] = None, + service: Optional[metastore.Service] = None, + service_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a metastore service in a 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 metastore_v1alpha + + def sample_create_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.CreateServiceRequest( + parent="parent_value", + service_id="service_id_value", + ) + + # Make the request + operation = client.create_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.CreateServiceRequest, dict]): + The request object. Request message for + [DataprocMetastore.CreateService][google.cloud.metastore.v1alpha.DataprocMetastore.CreateService]. + parent (str): + Required. The relative resource name of the location in + which to create a metastore service, in the following + form: + + ``projects/{project_number}/locations/{location_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service (google.cloud.metastore_v1alpha.types.Service): + Required. The Metastore service to create. The ``name`` + field is ignored. The ID of the created metastore + service must be provided in the request's ``service_id`` + field. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_id (str): + Required. The ID of the metastore + service, which is used as the final + component of the metastore service's + name. + This value must be between 2 and 63 + characters long inclusive, begin with a + letter, end with a letter or number, and + consist of alpha-numeric ASCII + characters or hyphens. + + This corresponds to the ``service_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1alpha.types.Service` A + managed metastore service that serves metadata queries. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, service, service_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a metastore.CreateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.CreateServiceRequest): + request = metastore.CreateServiceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if service is not None: + request.service = service + if service_id is not None: + request.service_id = service_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.Service, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_service(self, + request: Optional[Union[metastore.UpdateServiceRequest, dict]] = None, + *, + service: Optional[metastore.Service] = 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]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single service. + + .. 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 metastore_v1alpha + + def sample_update_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.UpdateServiceRequest( + ) + + # Make the request + operation = client.update_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.UpdateServiceRequest, dict]): + The request object. Request message for + [DataprocMetastore.UpdateService][google.cloud.metastore.v1alpha.DataprocMetastore.UpdateService]. + service (google.cloud.metastore_v1alpha.types.Service): + Required. The metastore service to update. The server + only merges fields in the service if they are specified + in ``update_mask``. + + The metastore service's ``name`` field is used to + identify the metastore service to be updated. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask used to specify the fields to be + overwritten in the metastore service resource by the + update. Fields specified in the ``update_mask`` are + relative to the resource (not to the full request). A + field is overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1alpha.types.Service` A + managed metastore service that serves metadata queries. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, 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 metastore.UpdateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.UpdateServiceRequest): + request = metastore.UpdateServiceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if service is not None: + request.service = service + 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_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service.name", request.service.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.Service, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_service(self, + request: Optional[Union[metastore.DeleteServiceRequest, 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]] = (), + ) -> operation.Operation: + r"""Deletes a single service. + + .. 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 metastore_v1alpha + + def sample_delete_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.DeleteServiceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.DeleteServiceRequest, dict]): + The request object. Request message for + [DataprocMetastore.DeleteService][google.cloud.metastore.v1alpha.DataprocMetastore.DeleteService]. + name (str): + Required. The relative resource name of the metastore + service to delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 metastore.DeleteServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.DeleteServiceRequest): + request = metastore.DeleteServiceRequest(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_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_metadata_imports(self, + request: Optional[Union[metastore.ListMetadataImportsRequest, 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.ListMetadataImportsPager: + r"""Lists imports in a service. + + .. 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 metastore_v1alpha + + def sample_list_metadata_imports(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ListMetadataImportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_metadata_imports(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.ListMetadataImportsRequest, dict]): + The request object. Request message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1alpha.DataprocMetastore.ListMetadataImports]. + parent (str): + Required. The relative resource name of the service + whose metadata imports to list, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports``. + + 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.metastore_v1alpha.services.dataproc_metastore.pagers.ListMetadataImportsPager: + Response message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1alpha.DataprocMetastore.ListMetadataImports]. + + 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 metastore.ListMetadataImportsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.ListMetadataImportsRequest): + request = metastore.ListMetadataImportsRequest(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_metadata_imports] + + # Certain 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.ListMetadataImportsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_metadata_import(self, + request: Optional[Union[metastore.GetMetadataImportRequest, 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]] = (), + ) -> metastore.MetadataImport: + r"""Gets details of a single import. + + .. 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 metastore_v1alpha + + def sample_get_metadata_import(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.GetMetadataImportRequest( + name="name_value", + ) + + # Make the request + response = client.get_metadata_import(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.GetMetadataImportRequest, dict]): + The request object. Request message for + [DataprocMetastore.GetMetadataImport][google.cloud.metastore.v1alpha.DataprocMetastore.GetMetadataImport]. + name (str): + Required. The relative resource name of the metadata + import to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports/{import_id}``. + + 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.metastore_v1alpha.types.MetadataImport: + A metastore resource that imports + 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 metastore.GetMetadataImportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.GetMetadataImportRequest): + request = metastore.GetMetadataImportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_metadata_import] + + # Certain 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_metadata_import(self, + request: Optional[Union[metastore.CreateMetadataImportRequest, dict]] = None, + *, + parent: Optional[str] = None, + metadata_import: Optional[metastore.MetadataImport] = None, + metadata_import_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new MetadataImport 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 metastore_v1alpha + + def sample_create_metadata_import(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.CreateMetadataImportRequest( + parent="parent_value", + metadata_import_id="metadata_import_id_value", + ) + + # Make the request + operation = client.create_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.CreateMetadataImportRequest, dict]): + The request object. Request message for + [DataprocMetastore.CreateMetadataImport][google.cloud.metastore.v1alpha.DataprocMetastore.CreateMetadataImport]. + parent (str): + Required. The relative resource name of the service in + which to create a metastore import, in the following + form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + metadata_import (google.cloud.metastore_v1alpha.types.MetadataImport): + Required. The metadata import to create. The ``name`` + field is ignored. The ID of the created metadata import + must be provided in the request's ``metadata_import_id`` + field. + + This corresponds to the ``metadata_import`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + metadata_import_id (str): + Required. The ID of the metadata + import, which is used as the final + component of the metadata import's name. + This value must be between 1 and 64 + characters long, begin with a letter, + end with a letter or number, and consist + of alpha-numeric ASCII characters or + hyphens. + + This corresponds to the ``metadata_import_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1alpha.types.MetadataImport` + A metastore resource that imports 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([parent, metadata_import, metadata_import_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a metastore.CreateMetadataImportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.CreateMetadataImportRequest): + request = metastore.CreateMetadataImportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if metadata_import is not None: + request.metadata_import = metadata_import + if metadata_import_id is not None: + request.metadata_import_id = metadata_import_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_metadata_import] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.MetadataImport, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_metadata_import(self, + request: Optional[Union[metastore.UpdateMetadataImportRequest, dict]] = None, + *, + metadata_import: Optional[metastore.MetadataImport] = 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]] = (), + ) -> operation.Operation: + r"""Updates a single import. + Only the description field of MetadataImport is + supported to be updated. + + .. 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 metastore_v1alpha + + def sample_update_metadata_import(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.UpdateMetadataImportRequest( + ) + + # Make the request + operation = client.update_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.UpdateMetadataImportRequest, dict]): + The request object. Request message for + [DataprocMetastore.UpdateMetadataImport][google.cloud.metastore.v1alpha.DataprocMetastore.UpdateMetadataImport]. + metadata_import (google.cloud.metastore_v1alpha.types.MetadataImport): + Required. The metadata import to update. The server only + merges fields in the import if they are specified in + ``update_mask``. + + The metadata import's ``name`` field is used to identify + the metastore import to be updated. + + This corresponds to the ``metadata_import`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask used to specify the fields to be + overwritten in the metadata import resource by the + update. Fields specified in the ``update_mask`` are + relative to the resource (not to the full request). A + field is overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1alpha.types.MetadataImport` + A metastore resource that imports 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([metadata_import, 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 metastore.UpdateMetadataImportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.UpdateMetadataImportRequest): + request = metastore.UpdateMetadataImportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if metadata_import is not None: + request.metadata_import = metadata_import + 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_metadata_import] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("metadata_import.name", request.metadata_import.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.MetadataImport, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def export_metadata(self, + request: Optional[Union[metastore.ExportMetadataRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports metadata from a service. + + .. 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 metastore_v1alpha + + def sample_export_metadata(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ExportMetadataRequest( + destination_gcs_folder="destination_gcs_folder_value", + service="service_value", + ) + + # Make the request + operation = client.export_metadata(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.ExportMetadataRequest, dict]): + The request object. Request message for + [DataprocMetastore.ExportMetadata][google.cloud.metastore.v1alpha.DataprocMetastore.ExportMetadata]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1alpha.types.MetadataExport` + The details of a metadata export operation. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a metastore.ExportMetadataRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.ExportMetadataRequest): + request = metastore.ExportMetadataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_metadata] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service", request.service), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.MetadataExport, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def restore_service(self, + request: Optional[Union[metastore.RestoreServiceRequest, dict]] = None, + *, + service: Optional[str] = None, + backup: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Restores a service from a backup. + + .. 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 metastore_v1alpha + + def sample_restore_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.RestoreServiceRequest( + service="service_value", + backup="backup_value", + ) + + # Make the request + operation = client.restore_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.RestoreServiceRequest, dict]): + The request object. Request message for [DataprocMetastore.Restore][]. + service (str): + Required. The relative resource name of the metastore + service to run restore, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup (str): + Required. The relative resource name of the metastore + service backup to restore from, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1alpha.types.Restore` + The details of a metadata restore operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, backup]) + if request is 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 metastore.RestoreServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.RestoreServiceRequest): + request = metastore.RestoreServiceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if service is not None: + request.service = service + if backup is not None: + request.backup = backup + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.restore_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service", request.service), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.Restore, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_backups(self, + request: Optional[Union[metastore.ListBackupsRequest, 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.ListBackupsPager: + r"""Lists backups in a service. + + .. 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 metastore_v1alpha + + def sample_list_backups(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.ListBackupsRequest, dict]): + The request object. Request message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1alpha.DataprocMetastore.ListBackups]. + parent (str): + Required. The relative resource name of the service + whose backups to list, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups``. + + 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.metastore_v1alpha.services.dataproc_metastore.pagers.ListBackupsPager: + Response message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1alpha.DataprocMetastore.ListBackups]. + + 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 metastore.ListBackupsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.ListBackupsRequest): + request = metastore.ListBackupsRequest(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_backups] + + # Certain 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.ListBackupsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_backup(self, + request: Optional[Union[metastore.GetBackupRequest, 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]] = (), + ) -> metastore.Backup: + r"""Gets details of a single backup. + + .. 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 metastore_v1alpha + + def sample_get_backup(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.GetBackupRequest, dict]): + The request object. Request message for + [DataprocMetastore.GetBackup][google.cloud.metastore.v1alpha.DataprocMetastore.GetBackup]. + name (str): + Required. The relative resource name of the backup to + retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + + 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.metastore_v1alpha.types.Backup: + The details of a backup resource. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a metastore.GetBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.GetBackupRequest): + request = metastore.GetBackupRequest(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_backup] + + # Certain 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_backup(self, + request: Optional[Union[metastore.CreateBackupRequest, dict]] = None, + *, + parent: Optional[str] = None, + backup: Optional[metastore.Backup] = None, + backup_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new backup 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 metastore_v1alpha + + def sample_create_backup(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + ) + + # Make the request + operation = client.create_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.CreateBackupRequest, dict]): + The request object. Request message for + [DataprocMetastore.CreateBackup][google.cloud.metastore.v1alpha.DataprocMetastore.CreateBackup]. + parent (str): + Required. The relative resource name of the service in + which to create a backup of the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup (google.cloud.metastore_v1alpha.types.Backup): + Required. The backup to create. The ``name`` field is + ignored. The ID of the created backup must be provided + in the request's ``backup_id`` field. + + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_id (str): + Required. The ID of the backup, which + is used as the final component of the + backup's name. + This value must be between 1 and 64 + characters long, begin with a letter, + end with a letter or number, and consist + of alpha-numeric ASCII characters or + hyphens. + + This corresponds to the ``backup_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1alpha.types.Backup` The + details of a backup resource. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, backup, backup_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a metastore.CreateBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.CreateBackupRequest): + request = metastore.CreateBackupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if backup is not None: + request.backup = backup + if backup_id is not None: + request.backup_id = backup_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_backup] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.Backup, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_backup(self, + request: Optional[Union[metastore.DeleteBackupRequest, 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]] = (), + ) -> operation.Operation: + r"""Deletes a single backup. + + .. 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 metastore_v1alpha + + def sample_delete_backup(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.DeleteBackupRequest, dict]): + The request object. Request message for + [DataprocMetastore.DeleteBackup][google.cloud.metastore.v1alpha.DataprocMetastore.DeleteBackup]. + name (str): + Required. The relative resource name of the backup to + delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 metastore.DeleteBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.DeleteBackupRequest): + request = metastore.DeleteBackupRequest(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_backup] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def remove_iam_policy(self, + request: Optional[Union[metastore.RemoveIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> metastore.RemoveIamPolicyResponse: + r"""Removes the attached IAM policies for a resource + + .. 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 metastore_v1alpha + + def sample_remove_iam_policy(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.RemoveIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.remove_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.RemoveIamPolicyRequest, dict]): + The request object. Request message for + [DataprocMetastore.RemoveIamPolicy][google.cloud.metastore.v1alpha.DataprocMetastore.RemoveIamPolicy]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.metastore_v1alpha.types.RemoveIamPolicyResponse: + Response message for + [DataprocMetastore.RemoveIamPolicy][google.cloud.metastore.v1alpha.DataprocMetastore.RemoveIamPolicy]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a metastore.RemoveIamPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.RemoveIamPolicyRequest): + request = metastore.RemoveIamPolicyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def query_metadata(self, + request: Optional[Union[metastore.QueryMetadataRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Query DPMS metadata. + + .. 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 metastore_v1alpha + + def sample_query_metadata(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.QueryMetadataRequest( + service="service_value", + query="query_value", + ) + + # Make the request + operation = client.query_metadata(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.QueryMetadataRequest, dict]): + The request object. Request message for + [DataprocMetastore.QueryMetadata][google.cloud.metastore.v1alpha.DataprocMetastore.QueryMetadata]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.metastore_v1alpha.types.QueryMetadataResponse` Response message for + [DataprocMetastore.QueryMetadata][google.cloud.metastore.v1alpha.DataprocMetastore.QueryMetadata]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a metastore.QueryMetadataRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.QueryMetadataRequest): + request = metastore.QueryMetadataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.query_metadata] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service", request.service), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.QueryMetadataResponse, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def move_table_to_database(self, + request: Optional[Union[metastore.MoveTableToDatabaseRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Move a table to another database. + + .. 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 metastore_v1alpha + + def sample_move_table_to_database(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.MoveTableToDatabaseRequest( + service="service_value", + table_name="table_name_value", + db_name="db_name_value", + destination_db_name="destination_db_name_value", + ) + + # Make the request + operation = client.move_table_to_database(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.MoveTableToDatabaseRequest, dict]): + The request object. Request message for + [DataprocMetastore.MoveTableToDatabase][google.cloud.metastore.v1alpha.DataprocMetastore.MoveTableToDatabase]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.metastore_v1alpha.types.MoveTableToDatabaseResponse` Response message for + [DataprocMetastore.MoveTableToDatabase][google.cloud.metastore.v1alpha.DataprocMetastore.MoveTableToDatabase]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a metastore.MoveTableToDatabaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.MoveTableToDatabaseRequest): + request = metastore.MoveTableToDatabaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.move_table_to_database] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service", request.service), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.MoveTableToDatabaseResponse, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def alter_metadata_resource_location(self, + request: Optional[Union[metastore.AlterMetadataResourceLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Alter metadata resource location. The metadata + resource can be a database, table, or partition. This + functionality only updates the parent directory for the + respective metadata resource and does not transfer any + existing data to the new 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 metastore_v1alpha + + def sample_alter_metadata_resource_location(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.AlterMetadataResourceLocationRequest( + service="service_value", + resource_name="resource_name_value", + location_uri="location_uri_value", + ) + + # Make the request + operation = client.alter_metadata_resource_location(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.AlterMetadataResourceLocationRequest, dict]): + The request object. Request message for + [DataprocMetastore.AlterMetadataResourceLocation][google.cloud.metastore.v1alpha.DataprocMetastore.AlterMetadataResourceLocation]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.metastore_v1alpha.types.AlterMetadataResourceLocationResponse` Response message for + [DataprocMetastore.AlterMetadataResourceLocation][google.cloud.metastore.v1alpha.DataprocMetastore.AlterMetadataResourceLocation]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a metastore.AlterMetadataResourceLocationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.AlterMetadataResourceLocationRequest): + request = metastore.AlterMetadataResourceLocationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.alter_metadata_resource_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service", request.service), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.AlterMetadataResourceLocationResponse, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "DataprocMetastoreClient": + 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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__ = ( + "DataprocMetastoreClient", +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/pagers.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/pagers.py new file mode 100644 index 0000000..83843d8 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/pagers.py @@ -0,0 +1,381 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.metastore_v1alpha.types import metastore + + +class ListServicesPager: + """A pager for iterating through ``list_services`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1alpha.types.ListServicesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``services`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServices`` requests and continue to iterate + through the ``services`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1alpha.types.ListServicesResponse` + 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[..., metastore.ListServicesResponse], + request: metastore.ListServicesRequest, + response: metastore.ListServicesResponse, + *, + 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.metastore_v1alpha.types.ListServicesRequest): + The initial request object. + response (google.cloud.metastore_v1alpha.types.ListServicesResponse): + 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 = metastore.ListServicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[metastore.ListServicesResponse]: + 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[metastore.Service]: + for page in self.pages: + yield from page.services + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServicesAsyncPager: + """A pager for iterating through ``list_services`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1alpha.types.ListServicesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``services`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServices`` requests and continue to iterate + through the ``services`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1alpha.types.ListServicesResponse` + 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[metastore.ListServicesResponse]], + request: metastore.ListServicesRequest, + response: metastore.ListServicesResponse, + *, + 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.metastore_v1alpha.types.ListServicesRequest): + The initial request object. + response (google.cloud.metastore_v1alpha.types.ListServicesResponse): + 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 = metastore.ListServicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[metastore.ListServicesResponse]: + 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[metastore.Service]: + async def async_generator(): + async for page in self.pages: + for response in page.services: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMetadataImportsPager: + """A pager for iterating through ``list_metadata_imports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1alpha.types.ListMetadataImportsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``metadata_imports`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMetadataImports`` requests and continue to iterate + through the ``metadata_imports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1alpha.types.ListMetadataImportsResponse` + 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[..., metastore.ListMetadataImportsResponse], + request: metastore.ListMetadataImportsRequest, + response: metastore.ListMetadataImportsResponse, + *, + 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.metastore_v1alpha.types.ListMetadataImportsRequest): + The initial request object. + response (google.cloud.metastore_v1alpha.types.ListMetadataImportsResponse): + 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 = metastore.ListMetadataImportsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[metastore.ListMetadataImportsResponse]: + 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[metastore.MetadataImport]: + for page in self.pages: + yield from page.metadata_imports + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMetadataImportsAsyncPager: + """A pager for iterating through ``list_metadata_imports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1alpha.types.ListMetadataImportsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``metadata_imports`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMetadataImports`` requests and continue to iterate + through the ``metadata_imports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1alpha.types.ListMetadataImportsResponse` + 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[metastore.ListMetadataImportsResponse]], + request: metastore.ListMetadataImportsRequest, + response: metastore.ListMetadataImportsResponse, + *, + 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.metastore_v1alpha.types.ListMetadataImportsRequest): + The initial request object. + response (google.cloud.metastore_v1alpha.types.ListMetadataImportsResponse): + 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 = metastore.ListMetadataImportsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[metastore.ListMetadataImportsResponse]: + 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[metastore.MetadataImport]: + async def async_generator(): + async for page in self.pages: + for response in page.metadata_imports: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBackupsPager: + """A pager for iterating through ``list_backups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1alpha.types.ListBackupsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``backups`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBackups`` requests and continue to iterate + through the ``backups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1alpha.types.ListBackupsResponse` + 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[..., metastore.ListBackupsResponse], + request: metastore.ListBackupsRequest, + response: metastore.ListBackupsResponse, + *, + 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.metastore_v1alpha.types.ListBackupsRequest): + The initial request object. + response (google.cloud.metastore_v1alpha.types.ListBackupsResponse): + 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 = metastore.ListBackupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[metastore.ListBackupsResponse]: + 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[metastore.Backup]: + for page in self.pages: + yield from page.backups + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBackupsAsyncPager: + """A pager for iterating through ``list_backups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1alpha.types.ListBackupsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``backups`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBackups`` requests and continue to iterate + through the ``backups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1alpha.types.ListBackupsResponse` + 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[metastore.ListBackupsResponse]], + request: metastore.ListBackupsRequest, + response: metastore.ListBackupsResponse, + *, + 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.metastore_v1alpha.types.ListBackupsRequest): + The initial request object. + response (google.cloud.metastore_v1alpha.types.ListBackupsResponse): + 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 = metastore.ListBackupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[metastore.ListBackupsResponse]: + 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[metastore.Backup]: + async def async_generator(): + async for page in self.pages: + for response in page.backups: + 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/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/__init__.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/__init__.py new file mode 100644 index 0000000..38e3513 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import DataprocMetastoreTransport +from .grpc import DataprocMetastoreGrpcTransport +from .grpc_asyncio import DataprocMetastoreGrpcAsyncIOTransport +from .rest import DataprocMetastoreRestTransport +from .rest import DataprocMetastoreRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DataprocMetastoreTransport]] +_transport_registry['grpc'] = DataprocMetastoreGrpcTransport +_transport_registry['grpc_asyncio'] = DataprocMetastoreGrpcAsyncIOTransport +_transport_registry['rest'] = DataprocMetastoreRestTransport + +__all__ = ( + 'DataprocMetastoreTransport', + 'DataprocMetastoreGrpcTransport', + 'DataprocMetastoreGrpcAsyncIOTransport', + 'DataprocMetastoreRestTransport', + 'DataprocMetastoreRestInterceptor', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/base.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/base.py new file mode 100644 index 0000000..745f71a --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/base.py @@ -0,0 +1,484 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.metastore_v1alpha import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1alpha.types import metastore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class DataprocMetastoreTransport(abc.ABC): + """Abstract transport class for DataprocMetastore.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'metastore.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_services: gapic_v1.method.wrap_method( + self.list_services, + default_timeout=None, + client_info=client_info, + ), + self.get_service: gapic_v1.method.wrap_method( + self.get_service, + default_timeout=None, + client_info=client_info, + ), + self.create_service: gapic_v1.method.wrap_method( + self.create_service, + default_timeout=60.0, + client_info=client_info, + ), + self.update_service: gapic_v1.method.wrap_method( + self.update_service, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_service: gapic_v1.method.wrap_method( + self.delete_service, + default_timeout=60.0, + client_info=client_info, + ), + self.list_metadata_imports: gapic_v1.method.wrap_method( + self.list_metadata_imports, + default_timeout=None, + client_info=client_info, + ), + self.get_metadata_import: gapic_v1.method.wrap_method( + self.get_metadata_import, + default_timeout=None, + client_info=client_info, + ), + self.create_metadata_import: gapic_v1.method.wrap_method( + self.create_metadata_import, + default_timeout=60.0, + client_info=client_info, + ), + self.update_metadata_import: gapic_v1.method.wrap_method( + self.update_metadata_import, + default_timeout=60.0, + client_info=client_info, + ), + self.export_metadata: gapic_v1.method.wrap_method( + self.export_metadata, + default_timeout=60.0, + client_info=client_info, + ), + self.restore_service: gapic_v1.method.wrap_method( + self.restore_service, + default_timeout=60.0, + client_info=client_info, + ), + self.list_backups: gapic_v1.method.wrap_method( + self.list_backups, + default_timeout=None, + client_info=client_info, + ), + self.get_backup: gapic_v1.method.wrap_method( + self.get_backup, + default_timeout=None, + client_info=client_info, + ), + self.create_backup: gapic_v1.method.wrap_method( + self.create_backup, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_backup: gapic_v1.method.wrap_method( + self.delete_backup, + default_timeout=60.0, + client_info=client_info, + ), + self.remove_iam_policy: gapic_v1.method.wrap_method( + self.remove_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.query_metadata: gapic_v1.method.wrap_method( + self.query_metadata, + default_timeout=None, + client_info=client_info, + ), + self.move_table_to_database: gapic_v1.method.wrap_method( + self.move_table_to_database, + default_timeout=None, + client_info=client_info, + ), + self.alter_metadata_resource_location: gapic_v1.method.wrap_method( + self.alter_metadata_resource_location, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_services(self) -> Callable[ + [metastore.ListServicesRequest], + Union[ + metastore.ListServicesResponse, + Awaitable[metastore.ListServicesResponse] + ]]: + raise NotImplementedError() + + @property + def get_service(self) -> Callable[ + [metastore.GetServiceRequest], + Union[ + metastore.Service, + Awaitable[metastore.Service] + ]]: + raise NotImplementedError() + + @property + def create_service(self) -> Callable[ + [metastore.CreateServiceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_service(self) -> Callable[ + [metastore.UpdateServiceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_service(self) -> Callable[ + [metastore.DeleteServiceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_metadata_imports(self) -> Callable[ + [metastore.ListMetadataImportsRequest], + Union[ + metastore.ListMetadataImportsResponse, + Awaitable[metastore.ListMetadataImportsResponse] + ]]: + raise NotImplementedError() + + @property + def get_metadata_import(self) -> Callable[ + [metastore.GetMetadataImportRequest], + Union[ + metastore.MetadataImport, + Awaitable[metastore.MetadataImport] + ]]: + raise NotImplementedError() + + @property + def create_metadata_import(self) -> Callable[ + [metastore.CreateMetadataImportRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_metadata_import(self) -> Callable[ + [metastore.UpdateMetadataImportRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def export_metadata(self) -> Callable[ + [metastore.ExportMetadataRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def restore_service(self) -> Callable[ + [metastore.RestoreServiceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_backups(self) -> Callable[ + [metastore.ListBackupsRequest], + Union[ + metastore.ListBackupsResponse, + Awaitable[metastore.ListBackupsResponse] + ]]: + raise NotImplementedError() + + @property + def get_backup(self) -> Callable[ + [metastore.GetBackupRequest], + Union[ + metastore.Backup, + Awaitable[metastore.Backup] + ]]: + raise NotImplementedError() + + @property + def create_backup(self) -> Callable[ + [metastore.CreateBackupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_backup(self) -> Callable[ + [metastore.DeleteBackupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_iam_policy(self) -> Callable[ + [metastore.RemoveIamPolicyRequest], + Union[ + metastore.RemoveIamPolicyResponse, + Awaitable[metastore.RemoveIamPolicyResponse] + ]]: + raise NotImplementedError() + + @property + def query_metadata(self) -> Callable[ + [metastore.QueryMetadataRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def move_table_to_database(self) -> Callable[ + [metastore.MoveTableToDatabaseRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def alter_metadata_resource_location(self) -> Callable[ + [metastore.AlterMetadataResourceLocationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + 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 delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + 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__ = ( + 'DataprocMetastoreTransport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/grpc.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/grpc.py new file mode 100644 index 0000000..4f8976c --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/grpc.py @@ -0,0 +1,954 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1alpha.types import metastore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from .base import DataprocMetastoreTransport, DEFAULT_CLIENT_INFO + + +class DataprocMetastoreGrpcTransport(DataprocMetastoreTransport): + """gRPC backend transport for DataprocMetastore. + + Configures and manages metastore services. Metastore services are + fully managed, highly available, autoscaled, autohealing, OSS-native + deployments of technical metadata management software. Each + metastore service exposes a network endpoint through which metadata + queries are served. Metadata queries can originate from a variety of + sources, including Apache Hive, Apache Presto, and Apache Spark. + + The Dataproc Metastore API defines the following resource model: + + - The service works with a collection of Google Cloud projects, + named: ``/projects/*`` + + - Each project has a collection of available locations, named: + ``/locations/*`` (a location must refer to a Google Cloud + ``region``) + + - Each location has a collection of services, named: + ``/services/*`` + + - Dataproc Metastore services are resources with names of the form: + + ``/projects/{project_number}/locations/{location_id}/services/{service_id}``. + + 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 = 'metastore.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] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + 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 = 'metastore.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 operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_services(self) -> Callable[ + [metastore.ListServicesRequest], + metastore.ListServicesResponse]: + r"""Return a callable for the list services method over gRPC. + + Lists services in a project and location. + + Returns: + Callable[[~.ListServicesRequest], + ~.ListServicesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_services' not in self._stubs: + self._stubs['list_services'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/ListServices', + request_serializer=metastore.ListServicesRequest.serialize, + response_deserializer=metastore.ListServicesResponse.deserialize, + ) + return self._stubs['list_services'] + + @property + def get_service(self) -> Callable[ + [metastore.GetServiceRequest], + metastore.Service]: + r"""Return a callable for the get service method over gRPC. + + Gets the details of a single service. + + Returns: + Callable[[~.GetServiceRequest], + ~.Service]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_service' not in self._stubs: + self._stubs['get_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/GetService', + request_serializer=metastore.GetServiceRequest.serialize, + response_deserializer=metastore.Service.deserialize, + ) + return self._stubs['get_service'] + + @property + def create_service(self) -> Callable[ + [metastore.CreateServiceRequest], + operations_pb2.Operation]: + r"""Return a callable for the create service method over gRPC. + + Creates a metastore service in a project and + location. + + Returns: + Callable[[~.CreateServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_service' not in self._stubs: + self._stubs['create_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/CreateService', + request_serializer=metastore.CreateServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_service'] + + @property + def update_service(self) -> Callable[ + [metastore.UpdateServiceRequest], + operations_pb2.Operation]: + r"""Return a callable for the update service method over gRPC. + + Updates the parameters of a single service. + + Returns: + Callable[[~.UpdateServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_service' not in self._stubs: + self._stubs['update_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/UpdateService', + request_serializer=metastore.UpdateServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_service'] + + @property + def delete_service(self) -> Callable[ + [metastore.DeleteServiceRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete service method over gRPC. + + Deletes a single service. + + Returns: + Callable[[~.DeleteServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_service' not in self._stubs: + self._stubs['delete_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/DeleteService', + request_serializer=metastore.DeleteServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_service'] + + @property + def list_metadata_imports(self) -> Callable[ + [metastore.ListMetadataImportsRequest], + metastore.ListMetadataImportsResponse]: + r"""Return a callable for the list metadata imports method over gRPC. + + Lists imports in a service. + + Returns: + Callable[[~.ListMetadataImportsRequest], + ~.ListMetadataImportsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_metadata_imports' not in self._stubs: + self._stubs['list_metadata_imports'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/ListMetadataImports', + request_serializer=metastore.ListMetadataImportsRequest.serialize, + response_deserializer=metastore.ListMetadataImportsResponse.deserialize, + ) + return self._stubs['list_metadata_imports'] + + @property + def get_metadata_import(self) -> Callable[ + [metastore.GetMetadataImportRequest], + metastore.MetadataImport]: + r"""Return a callable for the get metadata import method over gRPC. + + Gets details of a single import. + + Returns: + Callable[[~.GetMetadataImportRequest], + ~.MetadataImport]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_metadata_import' not in self._stubs: + self._stubs['get_metadata_import'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/GetMetadataImport', + request_serializer=metastore.GetMetadataImportRequest.serialize, + response_deserializer=metastore.MetadataImport.deserialize, + ) + return self._stubs['get_metadata_import'] + + @property + def create_metadata_import(self) -> Callable[ + [metastore.CreateMetadataImportRequest], + operations_pb2.Operation]: + r"""Return a callable for the create metadata import method over gRPC. + + Creates a new MetadataImport in a given project and + location. + + Returns: + Callable[[~.CreateMetadataImportRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_metadata_import' not in self._stubs: + self._stubs['create_metadata_import'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/CreateMetadataImport', + request_serializer=metastore.CreateMetadataImportRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_metadata_import'] + + @property + def update_metadata_import(self) -> Callable[ + [metastore.UpdateMetadataImportRequest], + operations_pb2.Operation]: + r"""Return a callable for the update metadata import method over gRPC. + + Updates a single import. + Only the description field of MetadataImport is + supported to be updated. + + Returns: + Callable[[~.UpdateMetadataImportRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_metadata_import' not in self._stubs: + self._stubs['update_metadata_import'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/UpdateMetadataImport', + request_serializer=metastore.UpdateMetadataImportRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_metadata_import'] + + @property + def export_metadata(self) -> Callable[ + [metastore.ExportMetadataRequest], + operations_pb2.Operation]: + r"""Return a callable for the export metadata method over gRPC. + + Exports metadata from a service. + + Returns: + Callable[[~.ExportMetadataRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_metadata' not in self._stubs: + self._stubs['export_metadata'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/ExportMetadata', + request_serializer=metastore.ExportMetadataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_metadata'] + + @property + def restore_service(self) -> Callable[ + [metastore.RestoreServiceRequest], + operations_pb2.Operation]: + r"""Return a callable for the restore service method over gRPC. + + Restores a service from a backup. + + Returns: + Callable[[~.RestoreServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'restore_service' not in self._stubs: + self._stubs['restore_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/RestoreService', + request_serializer=metastore.RestoreServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_service'] + + @property + def list_backups(self) -> Callable[ + [metastore.ListBackupsRequest], + metastore.ListBackupsResponse]: + r"""Return a callable for the list backups method over gRPC. + + Lists backups in a service. + + Returns: + Callable[[~.ListBackupsRequest], + ~.ListBackupsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_backups' not in self._stubs: + self._stubs['list_backups'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/ListBackups', + request_serializer=metastore.ListBackupsRequest.serialize, + response_deserializer=metastore.ListBackupsResponse.deserialize, + ) + return self._stubs['list_backups'] + + @property + def get_backup(self) -> Callable[ + [metastore.GetBackupRequest], + metastore.Backup]: + r"""Return a callable for the get backup method over gRPC. + + Gets details of a single backup. + + Returns: + Callable[[~.GetBackupRequest], + ~.Backup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_backup' not in self._stubs: + self._stubs['get_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/GetBackup', + request_serializer=metastore.GetBackupRequest.serialize, + response_deserializer=metastore.Backup.deserialize, + ) + return self._stubs['get_backup'] + + @property + def create_backup(self) -> Callable[ + [metastore.CreateBackupRequest], + operations_pb2.Operation]: + r"""Return a callable for the create backup method over gRPC. + + Creates a new backup in a given project and location. + + Returns: + Callable[[~.CreateBackupRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_backup' not in self._stubs: + self._stubs['create_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/CreateBackup', + request_serializer=metastore.CreateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_backup'] + + @property + def delete_backup(self) -> Callable[ + [metastore.DeleteBackupRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete backup method over gRPC. + + Deletes a single backup. + + Returns: + Callable[[~.DeleteBackupRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_backup' not in self._stubs: + self._stubs['delete_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/DeleteBackup', + request_serializer=metastore.DeleteBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_backup'] + + @property + def remove_iam_policy(self) -> Callable[ + [metastore.RemoveIamPolicyRequest], + metastore.RemoveIamPolicyResponse]: + r"""Return a callable for the remove iam policy method over gRPC. + + Removes the attached IAM policies for a resource + + Returns: + Callable[[~.RemoveIamPolicyRequest], + ~.RemoveIamPolicyResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_iam_policy' not in self._stubs: + self._stubs['remove_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/RemoveIamPolicy', + request_serializer=metastore.RemoveIamPolicyRequest.serialize, + response_deserializer=metastore.RemoveIamPolicyResponse.deserialize, + ) + return self._stubs['remove_iam_policy'] + + @property + def query_metadata(self) -> Callable[ + [metastore.QueryMetadataRequest], + operations_pb2.Operation]: + r"""Return a callable for the query metadata method over gRPC. + + Query DPMS metadata. + + Returns: + Callable[[~.QueryMetadataRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'query_metadata' not in self._stubs: + self._stubs['query_metadata'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/QueryMetadata', + request_serializer=metastore.QueryMetadataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['query_metadata'] + + @property + def move_table_to_database(self) -> Callable[ + [metastore.MoveTableToDatabaseRequest], + operations_pb2.Operation]: + r"""Return a callable for the move table to database method over gRPC. + + Move a table to another database. + + Returns: + Callable[[~.MoveTableToDatabaseRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'move_table_to_database' not in self._stubs: + self._stubs['move_table_to_database'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/MoveTableToDatabase', + request_serializer=metastore.MoveTableToDatabaseRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['move_table_to_database'] + + @property + def alter_metadata_resource_location(self) -> Callable[ + [metastore.AlterMetadataResourceLocationRequest], + operations_pb2.Operation]: + r"""Return a callable for the alter metadata resource + location method over gRPC. + + Alter metadata resource location. The metadata + resource can be a database, table, or partition. This + functionality only updates the parent directory for the + respective metadata resource and does not transfer any + existing data to the new location. + + Returns: + Callable[[~.AlterMetadataResourceLocationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'alter_metadata_resource_location' not in self._stubs: + self._stubs['alter_metadata_resource_location'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/AlterMetadataResourceLocation', + request_serializer=metastore.AlterMetadataResourceLocationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['alter_metadata_resource_location'] + + 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 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 set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'DataprocMetastoreGrpcTransport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/grpc_asyncio.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/grpc_asyncio.py new file mode 100644 index 0000000..2233598 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/grpc_asyncio.py @@ -0,0 +1,953 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1alpha.types import metastore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from .base import DataprocMetastoreTransport, DEFAULT_CLIENT_INFO +from .grpc import DataprocMetastoreGrpcTransport + + +class DataprocMetastoreGrpcAsyncIOTransport(DataprocMetastoreTransport): + """gRPC AsyncIO backend transport for DataprocMetastore. + + Configures and manages metastore services. Metastore services are + fully managed, highly available, autoscaled, autohealing, OSS-native + deployments of technical metadata management software. Each + metastore service exposes a network endpoint through which metadata + queries are served. Metadata queries can originate from a variety of + sources, including Apache Hive, Apache Presto, and Apache Spark. + + The Dataproc Metastore API defines the following resource model: + + - The service works with a collection of Google Cloud projects, + named: ``/projects/*`` + + - Each project has a collection of available locations, named: + ``/locations/*`` (a location must refer to a Google Cloud + ``region``) + + - Each location has a collection of services, named: + ``/services/*`` + + - Dataproc Metastore services are resources with names of the form: + + ``/projects/{project_number}/locations/{location_id}/services/{service_id}``. + + 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 = 'metastore.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 = 'metastore.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] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + 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 operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_services(self) -> Callable[ + [metastore.ListServicesRequest], + Awaitable[metastore.ListServicesResponse]]: + r"""Return a callable for the list services method over gRPC. + + Lists services in a project and location. + + Returns: + Callable[[~.ListServicesRequest], + Awaitable[~.ListServicesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_services' not in self._stubs: + self._stubs['list_services'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/ListServices', + request_serializer=metastore.ListServicesRequest.serialize, + response_deserializer=metastore.ListServicesResponse.deserialize, + ) + return self._stubs['list_services'] + + @property + def get_service(self) -> Callable[ + [metastore.GetServiceRequest], + Awaitable[metastore.Service]]: + r"""Return a callable for the get service method over gRPC. + + Gets the details of a single service. + + Returns: + Callable[[~.GetServiceRequest], + Awaitable[~.Service]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_service' not in self._stubs: + self._stubs['get_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/GetService', + request_serializer=metastore.GetServiceRequest.serialize, + response_deserializer=metastore.Service.deserialize, + ) + return self._stubs['get_service'] + + @property + def create_service(self) -> Callable[ + [metastore.CreateServiceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create service method over gRPC. + + Creates a metastore service in a project and + location. + + Returns: + Callable[[~.CreateServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_service' not in self._stubs: + self._stubs['create_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/CreateService', + request_serializer=metastore.CreateServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_service'] + + @property + def update_service(self) -> Callable[ + [metastore.UpdateServiceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update service method over gRPC. + + Updates the parameters of a single service. + + Returns: + Callable[[~.UpdateServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_service' not in self._stubs: + self._stubs['update_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/UpdateService', + request_serializer=metastore.UpdateServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_service'] + + @property + def delete_service(self) -> Callable[ + [metastore.DeleteServiceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete service method over gRPC. + + Deletes a single service. + + Returns: + Callable[[~.DeleteServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_service' not in self._stubs: + self._stubs['delete_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/DeleteService', + request_serializer=metastore.DeleteServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_service'] + + @property + def list_metadata_imports(self) -> Callable[ + [metastore.ListMetadataImportsRequest], + Awaitable[metastore.ListMetadataImportsResponse]]: + r"""Return a callable for the list metadata imports method over gRPC. + + Lists imports in a service. + + Returns: + Callable[[~.ListMetadataImportsRequest], + Awaitable[~.ListMetadataImportsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_metadata_imports' not in self._stubs: + self._stubs['list_metadata_imports'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/ListMetadataImports', + request_serializer=metastore.ListMetadataImportsRequest.serialize, + response_deserializer=metastore.ListMetadataImportsResponse.deserialize, + ) + return self._stubs['list_metadata_imports'] + + @property + def get_metadata_import(self) -> Callable[ + [metastore.GetMetadataImportRequest], + Awaitable[metastore.MetadataImport]]: + r"""Return a callable for the get metadata import method over gRPC. + + Gets details of a single import. + + Returns: + Callable[[~.GetMetadataImportRequest], + Awaitable[~.MetadataImport]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_metadata_import' not in self._stubs: + self._stubs['get_metadata_import'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/GetMetadataImport', + request_serializer=metastore.GetMetadataImportRequest.serialize, + response_deserializer=metastore.MetadataImport.deserialize, + ) + return self._stubs['get_metadata_import'] + + @property + def create_metadata_import(self) -> Callable[ + [metastore.CreateMetadataImportRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create metadata import method over gRPC. + + Creates a new MetadataImport in a given project and + location. + + Returns: + Callable[[~.CreateMetadataImportRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_metadata_import' not in self._stubs: + self._stubs['create_metadata_import'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/CreateMetadataImport', + request_serializer=metastore.CreateMetadataImportRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_metadata_import'] + + @property + def update_metadata_import(self) -> Callable[ + [metastore.UpdateMetadataImportRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update metadata import method over gRPC. + + Updates a single import. + Only the description field of MetadataImport is + supported to be updated. + + Returns: + Callable[[~.UpdateMetadataImportRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_metadata_import' not in self._stubs: + self._stubs['update_metadata_import'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/UpdateMetadataImport', + request_serializer=metastore.UpdateMetadataImportRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_metadata_import'] + + @property + def export_metadata(self) -> Callable[ + [metastore.ExportMetadataRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the export metadata method over gRPC. + + Exports metadata from a service. + + Returns: + Callable[[~.ExportMetadataRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_metadata' not in self._stubs: + self._stubs['export_metadata'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/ExportMetadata', + request_serializer=metastore.ExportMetadataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_metadata'] + + @property + def restore_service(self) -> Callable[ + [metastore.RestoreServiceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the restore service method over gRPC. + + Restores a service from a backup. + + Returns: + Callable[[~.RestoreServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'restore_service' not in self._stubs: + self._stubs['restore_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/RestoreService', + request_serializer=metastore.RestoreServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_service'] + + @property + def list_backups(self) -> Callable[ + [metastore.ListBackupsRequest], + Awaitable[metastore.ListBackupsResponse]]: + r"""Return a callable for the list backups method over gRPC. + + Lists backups in a service. + + Returns: + Callable[[~.ListBackupsRequest], + Awaitable[~.ListBackupsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_backups' not in self._stubs: + self._stubs['list_backups'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/ListBackups', + request_serializer=metastore.ListBackupsRequest.serialize, + response_deserializer=metastore.ListBackupsResponse.deserialize, + ) + return self._stubs['list_backups'] + + @property + def get_backup(self) -> Callable[ + [metastore.GetBackupRequest], + Awaitable[metastore.Backup]]: + r"""Return a callable for the get backup method over gRPC. + + Gets details of a single backup. + + Returns: + Callable[[~.GetBackupRequest], + Awaitable[~.Backup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_backup' not in self._stubs: + self._stubs['get_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/GetBackup', + request_serializer=metastore.GetBackupRequest.serialize, + response_deserializer=metastore.Backup.deserialize, + ) + return self._stubs['get_backup'] + + @property + def create_backup(self) -> Callable[ + [metastore.CreateBackupRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create backup method over gRPC. + + Creates a new backup in a given project and location. + + Returns: + Callable[[~.CreateBackupRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_backup' not in self._stubs: + self._stubs['create_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/CreateBackup', + request_serializer=metastore.CreateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_backup'] + + @property + def delete_backup(self) -> Callable[ + [metastore.DeleteBackupRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete backup method over gRPC. + + Deletes a single backup. + + Returns: + Callable[[~.DeleteBackupRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_backup' not in self._stubs: + self._stubs['delete_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/DeleteBackup', + request_serializer=metastore.DeleteBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_backup'] + + @property + def remove_iam_policy(self) -> Callable[ + [metastore.RemoveIamPolicyRequest], + Awaitable[metastore.RemoveIamPolicyResponse]]: + r"""Return a callable for the remove iam policy method over gRPC. + + Removes the attached IAM policies for a resource + + Returns: + Callable[[~.RemoveIamPolicyRequest], + Awaitable[~.RemoveIamPolicyResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_iam_policy' not in self._stubs: + self._stubs['remove_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/RemoveIamPolicy', + request_serializer=metastore.RemoveIamPolicyRequest.serialize, + response_deserializer=metastore.RemoveIamPolicyResponse.deserialize, + ) + return self._stubs['remove_iam_policy'] + + @property + def query_metadata(self) -> Callable[ + [metastore.QueryMetadataRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the query metadata method over gRPC. + + Query DPMS metadata. + + Returns: + Callable[[~.QueryMetadataRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'query_metadata' not in self._stubs: + self._stubs['query_metadata'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/QueryMetadata', + request_serializer=metastore.QueryMetadataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['query_metadata'] + + @property + def move_table_to_database(self) -> Callable[ + [metastore.MoveTableToDatabaseRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the move table to database method over gRPC. + + Move a table to another database. + + Returns: + Callable[[~.MoveTableToDatabaseRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'move_table_to_database' not in self._stubs: + self._stubs['move_table_to_database'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/MoveTableToDatabase', + request_serializer=metastore.MoveTableToDatabaseRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['move_table_to_database'] + + @property + def alter_metadata_resource_location(self) -> Callable[ + [metastore.AlterMetadataResourceLocationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the alter metadata resource + location method over gRPC. + + Alter metadata resource location. The metadata + resource can be a database, table, or partition. This + functionality only updates the parent directory for the + respective metadata resource and does not transfer any + existing data to the new location. + + Returns: + Callable[[~.AlterMetadataResourceLocationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'alter_metadata_resource_location' not in self._stubs: + self._stubs['alter_metadata_resource_location'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastore/AlterMetadataResourceLocation', + request_serializer=metastore.AlterMetadataResourceLocationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['alter_metadata_resource_location'] + + 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 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 set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'DataprocMetastoreGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/rest.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/rest.py new file mode 100644 index 0000000..2234d3b --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/rest.py @@ -0,0 +1,3218 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +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.metastore_v1alpha.types import metastore +from google.longrunning import operations_pb2 # type: ignore + +from .base import DataprocMetastoreTransport, 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 DataprocMetastoreRestInterceptor: + """Interceptor for DataprocMetastore. + + 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 DataprocMetastoreRestTransport. + + .. code-block:: python + class MyCustomDataprocMetastoreInterceptor(DataprocMetastoreRestInterceptor): + def pre_alter_metadata_resource_location(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_alter_metadata_resource_location(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_metadata_import(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_metadata_import(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_export_metadata(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_export_metadata(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_metadata_import(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_metadata_import(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_backups(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_backups(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_metadata_imports(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_metadata_imports(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_services(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_services(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_move_table_to_database(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_move_table_to_database(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_query_metadata(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_query_metadata(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_remove_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_remove_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_restore_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_restore_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_metadata_import(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_metadata_import(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_service(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DataprocMetastoreRestTransport(interceptor=MyCustomDataprocMetastoreInterceptor()) + client = DataprocMetastoreClient(transport=transport) + + + """ + def pre_alter_metadata_resource_location(self, request: metastore.AlterMetadataResourceLocationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.AlterMetadataResourceLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for alter_metadata_resource_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_alter_metadata_resource_location(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for alter_metadata_resource_location + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_create_backup(self, request: metastore.CreateBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.CreateBackupRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_create_backup(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_backup + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_create_metadata_import(self, request: metastore.CreateMetadataImportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.CreateMetadataImportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_metadata_import + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_create_metadata_import(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_metadata_import + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_create_service(self, request: metastore.CreateServiceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.CreateServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_create_service(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_service + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_delete_backup(self, request: metastore.DeleteBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.DeleteBackupRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_delete_backup(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_backup + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_delete_service(self, request: metastore.DeleteServiceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.DeleteServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_delete_service(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_service + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_export_metadata(self, request: metastore.ExportMetadataRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.ExportMetadataRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for export_metadata + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_export_metadata(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for export_metadata + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_get_backup(self, request: metastore.GetBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.GetBackupRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_get_backup(self, response: metastore.Backup) -> metastore.Backup: + """Post-rpc interceptor for get_backup + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_get_metadata_import(self, request: metastore.GetMetadataImportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.GetMetadataImportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_metadata_import + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_get_metadata_import(self, response: metastore.MetadataImport) -> metastore.MetadataImport: + """Post-rpc interceptor for get_metadata_import + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_get_service(self, request: metastore.GetServiceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.GetServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_get_service(self, response: metastore.Service) -> metastore.Service: + """Post-rpc interceptor for get_service + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_list_backups(self, request: metastore.ListBackupsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.ListBackupsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_backups + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_list_backups(self, response: metastore.ListBackupsResponse) -> metastore.ListBackupsResponse: + """Post-rpc interceptor for list_backups + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_list_metadata_imports(self, request: metastore.ListMetadataImportsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.ListMetadataImportsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_metadata_imports + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_list_metadata_imports(self, response: metastore.ListMetadataImportsResponse) -> metastore.ListMetadataImportsResponse: + """Post-rpc interceptor for list_metadata_imports + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_list_services(self, request: metastore.ListServicesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.ListServicesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_services + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_list_services(self, response: metastore.ListServicesResponse) -> metastore.ListServicesResponse: + """Post-rpc interceptor for list_services + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_move_table_to_database(self, request: metastore.MoveTableToDatabaseRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.MoveTableToDatabaseRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for move_table_to_database + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_move_table_to_database(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for move_table_to_database + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_query_metadata(self, request: metastore.QueryMetadataRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.QueryMetadataRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for query_metadata + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_query_metadata(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for query_metadata + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_remove_iam_policy(self, request: metastore.RemoveIamPolicyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.RemoveIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for remove_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_remove_iam_policy(self, response: metastore.RemoveIamPolicyResponse) -> metastore.RemoveIamPolicyResponse: + """Post-rpc interceptor for remove_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_restore_service(self, request: metastore.RestoreServiceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.RestoreServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for restore_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_restore_service(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for restore_service + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_update_metadata_import(self, request: metastore.UpdateMetadataImportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.UpdateMetadataImportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_metadata_import + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_update_metadata_import(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_metadata_import + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_update_service(self, request: metastore.UpdateServiceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.UpdateServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_update_service(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_service + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DataprocMetastoreRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DataprocMetastoreRestInterceptor + + +class DataprocMetastoreRestTransport(DataprocMetastoreTransport): + """REST backend transport for DataprocMetastore. + + Configures and manages metastore services. Metastore services are + fully managed, highly available, autoscaled, autohealing, OSS-native + deployments of technical metadata management software. Each + metastore service exposes a network endpoint through which metadata + queries are served. Metadata queries can originate from a variety of + sources, including Apache Hive, Apache Presto, and Apache Spark. + + The Dataproc Metastore API defines the following resource model: + + - The service works with a collection of Google Cloud projects, + named: ``/projects/*`` + + - Each project has a collection of available locations, named: + ``/locations/*`` (a location must refer to a Google Cloud + ``region``) + + - Each location has a collection of services, named: + ``/services/*`` + + - Dataproc Metastore services are resources with names of the form: + + ``/projects/{project_number}/locations/{location_id}/services/{service_id}``. + + 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 = 'metastore.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[DataprocMetastoreRestInterceptor] = 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) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DataprocMetastoreRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1alpha") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _AlterMetadataResourceLocation(DataprocMetastoreRestStub): + def __hash__(self): + return hash("AlterMetadataResourceLocation") + + __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: metastore.AlterMetadataResourceLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the alter metadata resource + location method over HTTP. + + Args: + request (~.metastore.AlterMetadataResourceLocationRequest): + The request object. Request message for + [DataprocMetastore.AlterMetadataResourceLocation][google.cloud.metastore.v1alpha.DataprocMetastore.AlterMetadataResourceLocation]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{service=projects/*/locations/*/services/*}:alterLocation', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_alter_metadata_resource_location(request, metadata) + pb_request = metastore.AlterMetadataResourceLocationRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_alter_metadata_resource_location(resp) + return resp + + class _CreateBackup(DataprocMetastoreRestStub): + def __hash__(self): + return hash("CreateBackup") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "backupId" : "", } + + @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: metastore.CreateBackupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create backup method over HTTP. + + Args: + request (~.metastore.CreateBackupRequest): + The request object. Request message for + [DataprocMetastore.CreateBackup][google.cloud.metastore.v1alpha.DataprocMetastore.CreateBackup]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/services/*}/backups', + 'body': 'backup', + }, + ] + request, metadata = self._interceptor.pre_create_backup(request, metadata) + pb_request = metastore.CreateBackupRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_backup(resp) + return resp + + class _CreateMetadataImport(DataprocMetastoreRestStub): + def __hash__(self): + return hash("CreateMetadataImport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "metadataImportId" : "", } + + @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: metastore.CreateMetadataImportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create metadata import method over HTTP. + + Args: + request (~.metastore.CreateMetadataImportRequest): + The request object. Request message for + [DataprocMetastore.CreateMetadataImport][google.cloud.metastore.v1alpha.DataprocMetastore.CreateMetadataImport]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/services/*}/metadataImports', + 'body': 'metadata_import', + }, + ] + request, metadata = self._interceptor.pre_create_metadata_import(request, metadata) + pb_request = metastore.CreateMetadataImportRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_metadata_import(resp) + return resp + + class _CreateService(DataprocMetastoreRestStub): + def __hash__(self): + return hash("CreateService") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "serviceId" : "", } + + @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: metastore.CreateServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create service method over HTTP. + + Args: + request (~.metastore.CreateServiceRequest): + The request object. Request message for + [DataprocMetastore.CreateService][google.cloud.metastore.v1alpha.DataprocMetastore.CreateService]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*}/services', + 'body': 'service', + }, + ] + request, metadata = self._interceptor.pre_create_service(request, metadata) + pb_request = metastore.CreateServiceRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_service(resp) + return resp + + class _DeleteBackup(DataprocMetastoreRestStub): + def __hash__(self): + return hash("DeleteBackup") + + __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: metastore.DeleteBackupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete backup method over HTTP. + + Args: + request (~.metastore.DeleteBackupRequest): + The request object. Request message for + [DataprocMetastore.DeleteBackup][google.cloud.metastore.v1alpha.DataprocMetastore.DeleteBackup]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha/{name=projects/*/locations/*/services/*/backups/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_backup(request, metadata) + pb_request = metastore.DeleteBackupRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_backup(resp) + return resp + + class _DeleteService(DataprocMetastoreRestStub): + def __hash__(self): + return hash("DeleteService") + + __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: metastore.DeleteServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete service method over HTTP. + + Args: + request (~.metastore.DeleteServiceRequest): + The request object. Request message for + [DataprocMetastore.DeleteService][google.cloud.metastore.v1alpha.DataprocMetastore.DeleteService]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha/{name=projects/*/locations/*/services/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_service(request, metadata) + pb_request = metastore.DeleteServiceRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_service(resp) + return resp + + class _ExportMetadata(DataprocMetastoreRestStub): + def __hash__(self): + return hash("ExportMetadata") + + __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: metastore.ExportMetadataRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the export metadata method over HTTP. + + Args: + request (~.metastore.ExportMetadataRequest): + The request object. Request message for + [DataprocMetastore.ExportMetadata][google.cloud.metastore.v1alpha.DataprocMetastore.ExportMetadata]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{service=projects/*/locations/*/services/*}:exportMetadata', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_export_metadata(request, metadata) + pb_request = metastore.ExportMetadataRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_export_metadata(resp) + return resp + + class _GetBackup(DataprocMetastoreRestStub): + def __hash__(self): + return hash("GetBackup") + + __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: metastore.GetBackupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.Backup: + r"""Call the get backup method over HTTP. + + Args: + request (~.metastore.GetBackupRequest): + The request object. Request message for + [DataprocMetastore.GetBackup][google.cloud.metastore.v1alpha.DataprocMetastore.GetBackup]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.Backup: + The details of a backup resource. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/services/*/backups/*}', + }, + ] + request, metadata = self._interceptor.pre_get_backup(request, metadata) + pb_request = metastore.GetBackupRequest.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 = metastore.Backup() + pb_resp = metastore.Backup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_backup(resp) + return resp + + class _GetMetadataImport(DataprocMetastoreRestStub): + def __hash__(self): + return hash("GetMetadataImport") + + __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: metastore.GetMetadataImportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.MetadataImport: + r"""Call the get metadata import method over HTTP. + + Args: + request (~.metastore.GetMetadataImportRequest): + The request object. Request message for + [DataprocMetastore.GetMetadataImport][google.cloud.metastore.v1alpha.DataprocMetastore.GetMetadataImport]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.MetadataImport: + A metastore resource that imports + metadata. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/services/*/metadataImports/*}', + }, + ] + request, metadata = self._interceptor.pre_get_metadata_import(request, metadata) + pb_request = metastore.GetMetadataImportRequest.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 = metastore.MetadataImport() + pb_resp = metastore.MetadataImport.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_metadata_import(resp) + return resp + + class _GetService(DataprocMetastoreRestStub): + def __hash__(self): + return hash("GetService") + + __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: metastore.GetServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.Service: + r"""Call the get service method over HTTP. + + Args: + request (~.metastore.GetServiceRequest): + The request object. Request message for + [DataprocMetastore.GetService][google.cloud.metastore.v1alpha.DataprocMetastore.GetService]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.Service: + A managed metastore service that + serves metadata queries. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/services/*}', + }, + ] + request, metadata = self._interceptor.pre_get_service(request, metadata) + pb_request = metastore.GetServiceRequest.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 = metastore.Service() + pb_resp = metastore.Service.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_service(resp) + return resp + + class _ListBackups(DataprocMetastoreRestStub): + def __hash__(self): + return hash("ListBackups") + + __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: metastore.ListBackupsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.ListBackupsResponse: + r"""Call the list backups method over HTTP. + + Args: + request (~.metastore.ListBackupsRequest): + The request object. Request message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1alpha.DataprocMetastore.ListBackups]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.ListBackupsResponse: + Response message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1alpha.DataprocMetastore.ListBackups]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*/services/*}/backups', + }, + ] + request, metadata = self._interceptor.pre_list_backups(request, metadata) + pb_request = metastore.ListBackupsRequest.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 = metastore.ListBackupsResponse() + pb_resp = metastore.ListBackupsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_backups(resp) + return resp + + class _ListMetadataImports(DataprocMetastoreRestStub): + def __hash__(self): + return hash("ListMetadataImports") + + __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: metastore.ListMetadataImportsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.ListMetadataImportsResponse: + r"""Call the list metadata imports method over HTTP. + + Args: + request (~.metastore.ListMetadataImportsRequest): + The request object. Request message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1alpha.DataprocMetastore.ListMetadataImports]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.ListMetadataImportsResponse: + Response message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1alpha.DataprocMetastore.ListMetadataImports]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*/services/*}/metadataImports', + }, + ] + request, metadata = self._interceptor.pre_list_metadata_imports(request, metadata) + pb_request = metastore.ListMetadataImportsRequest.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 = metastore.ListMetadataImportsResponse() + pb_resp = metastore.ListMetadataImportsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_metadata_imports(resp) + return resp + + class _ListServices(DataprocMetastoreRestStub): + def __hash__(self): + return hash("ListServices") + + __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: metastore.ListServicesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.ListServicesResponse: + r"""Call the list services method over HTTP. + + Args: + request (~.metastore.ListServicesRequest): + The request object. Request message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1alpha.DataprocMetastore.ListServices]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.ListServicesResponse: + Response message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1alpha.DataprocMetastore.ListServices]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*}/services', + }, + ] + request, metadata = self._interceptor.pre_list_services(request, metadata) + pb_request = metastore.ListServicesRequest.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 = metastore.ListServicesResponse() + pb_resp = metastore.ListServicesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_services(resp) + return resp + + class _MoveTableToDatabase(DataprocMetastoreRestStub): + def __hash__(self): + return hash("MoveTableToDatabase") + + __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: metastore.MoveTableToDatabaseRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the move table to database method over HTTP. + + Args: + request (~.metastore.MoveTableToDatabaseRequest): + The request object. Request message for + [DataprocMetastore.MoveTableToDatabase][google.cloud.metastore.v1alpha.DataprocMetastore.MoveTableToDatabase]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{service=projects/*/locations/*/services/*}:moveTableToDatabase', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_move_table_to_database(request, metadata) + pb_request = metastore.MoveTableToDatabaseRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_move_table_to_database(resp) + return resp + + class _QueryMetadata(DataprocMetastoreRestStub): + def __hash__(self): + return hash("QueryMetadata") + + __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: metastore.QueryMetadataRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the query metadata method over HTTP. + + Args: + request (~.metastore.QueryMetadataRequest): + The request object. Request message for + [DataprocMetastore.QueryMetadata][google.cloud.metastore.v1alpha.DataprocMetastore.QueryMetadata]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{service=projects/*/locations/*/services/*}:queryMetadata', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_query_metadata(request, metadata) + pb_request = metastore.QueryMetadataRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_query_metadata(resp) + return resp + + class _RemoveIamPolicy(DataprocMetastoreRestStub): + def __hash__(self): + return hash("RemoveIamPolicy") + + __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: metastore.RemoveIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.RemoveIamPolicyResponse: + r"""Call the remove iam policy method over HTTP. + + Args: + request (~.metastore.RemoveIamPolicyRequest): + The request object. Request message for + [DataprocMetastore.RemoveIamPolicy][google.cloud.metastore.v1alpha.DataprocMetastore.RemoveIamPolicy]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.RemoveIamPolicyResponse: + Response message for + [DataprocMetastore.RemoveIamPolicy][google.cloud.metastore.v1alpha.DataprocMetastore.RemoveIamPolicy]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/**}:removeIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_remove_iam_policy(request, metadata) + pb_request = metastore.RemoveIamPolicyRequest.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 = metastore.RemoveIamPolicyResponse() + pb_resp = metastore.RemoveIamPolicyResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_remove_iam_policy(resp) + return resp + + class _RestoreService(DataprocMetastoreRestStub): + def __hash__(self): + return hash("RestoreService") + + __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: metastore.RestoreServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the restore service method over HTTP. + + Args: + request (~.metastore.RestoreServiceRequest): + The request object. Request message for [DataprocMetastore.Restore][]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{service=projects/*/locations/*/services/*}:restore', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_restore_service(request, metadata) + pb_request = metastore.RestoreServiceRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_restore_service(resp) + return resp + + class _UpdateMetadataImport(DataprocMetastoreRestStub): + def __hash__(self): + return hash("UpdateMetadataImport") + + __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: metastore.UpdateMetadataImportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update metadata import method over HTTP. + + Args: + request (~.metastore.UpdateMetadataImportRequest): + The request object. Request message for + [DataprocMetastore.UpdateMetadataImport][google.cloud.metastore.v1alpha.DataprocMetastore.UpdateMetadataImport]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{metadata_import.name=projects/*/locations/*/services/*/metadataImports/*}', + 'body': 'metadata_import', + }, + ] + request, metadata = self._interceptor.pre_update_metadata_import(request, metadata) + pb_request = metastore.UpdateMetadataImportRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_metadata_import(resp) + return resp + + class _UpdateService(DataprocMetastoreRestStub): + def __hash__(self): + return hash("UpdateService") + + __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: metastore.UpdateServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update service method over HTTP. + + Args: + request (~.metastore.UpdateServiceRequest): + The request object. Request message for + [DataprocMetastore.UpdateService][google.cloud.metastore.v1alpha.DataprocMetastore.UpdateService]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{service.name=projects/*/locations/*/services/*}', + 'body': 'service', + }, + ] + request, metadata = self._interceptor.pre_update_service(request, metadata) + pb_request = metastore.UpdateServiceRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_service(resp) + return resp + + @property + def alter_metadata_resource_location(self) -> Callable[ + [metastore.AlterMetadataResourceLocationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AlterMetadataResourceLocation(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_backup(self) -> Callable[ + [metastore.CreateBackupRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_metadata_import(self) -> Callable[ + [metastore.CreateMetadataImportRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateMetadataImport(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_service(self) -> Callable[ + [metastore.CreateServiceRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateService(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_backup(self) -> Callable[ + [metastore.DeleteBackupRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_service(self) -> Callable[ + [metastore.DeleteServiceRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteService(self._session, self._host, self._interceptor) # type: ignore + + @property + def export_metadata(self) -> Callable[ + [metastore.ExportMetadataRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ExportMetadata(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_backup(self) -> Callable[ + [metastore.GetBackupRequest], + metastore.Backup]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_metadata_import(self) -> Callable[ + [metastore.GetMetadataImportRequest], + metastore.MetadataImport]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetMetadataImport(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_service(self) -> Callable[ + [metastore.GetServiceRequest], + metastore.Service]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetService(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_backups(self) -> Callable[ + [metastore.ListBackupsRequest], + metastore.ListBackupsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListBackups(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_metadata_imports(self) -> Callable[ + [metastore.ListMetadataImportsRequest], + metastore.ListMetadataImportsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListMetadataImports(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_services(self) -> Callable[ + [metastore.ListServicesRequest], + metastore.ListServicesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListServices(self._session, self._host, self._interceptor) # type: ignore + + @property + def move_table_to_database(self) -> Callable[ + [metastore.MoveTableToDatabaseRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._MoveTableToDatabase(self._session, self._host, self._interceptor) # type: ignore + + @property + def query_metadata(self) -> Callable[ + [metastore.QueryMetadataRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._QueryMetadata(self._session, self._host, self._interceptor) # type: ignore + + @property + def remove_iam_policy(self) -> Callable[ + [metastore.RemoveIamPolicyRequest], + metastore.RemoveIamPolicyResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RemoveIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def restore_service(self) -> Callable[ + [metastore.RestoreServiceRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RestoreService(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_metadata_import(self) -> Callable[ + [metastore.UpdateMetadataImportRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMetadataImport(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_service(self) -> Callable[ + [metastore.UpdateServiceRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateService(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(DataprocMetastoreRestStub): + 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': '/v1alpha/{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(DataprocMetastoreRestStub): + 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': '/v1alpha/{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 get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(DataprocMetastoreRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy 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: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/backups/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/databases/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/databases/*/tables/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{resource=projects/*/locations/*/federations/*}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(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 = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(DataprocMetastoreRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy 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: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/backups/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/databases/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/databases/*/tables/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/federations/*}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.loads(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) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(DataprocMetastoreRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions 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: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/backups/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/databases/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/databases/*/tables/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/federations/*}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.loads(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) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(DataprocMetastoreRestStub): + 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': '/v1alpha/{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(DataprocMetastoreRestStub): + 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': '/v1alpha/{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(DataprocMetastoreRestStub): + 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': '/v1alpha/{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__=( + 'DataprocMetastoreRestTransport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/__init__.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/__init__.py new file mode 100644 index 0000000..7029be0 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import DataprocMetastoreFederationClient +from .async_client import DataprocMetastoreFederationAsyncClient + +__all__ = ( + 'DataprocMetastoreFederationClient', + 'DataprocMetastoreFederationAsyncClient', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/async_client.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/async_client.py new file mode 100644 index 0000000..1b0d0d8 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/async_client.py @@ -0,0 +1,1388 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.metastore_v1alpha import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1alpha.services.dataproc_metastore_federation import pagers +from google.cloud.metastore_v1alpha.types import metastore +from google.cloud.metastore_v1alpha.types import metastore_federation +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DataprocMetastoreFederationTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DataprocMetastoreFederationGrpcAsyncIOTransport +from .client import DataprocMetastoreFederationClient + + +class DataprocMetastoreFederationAsyncClient: + """Configures and manages metastore federation services. Dataproc + Metastore Federation Service allows federating a collection of + backend metastores like BigQuery, Dataplex Lakes, and other Dataproc + Metastores. The Federation Service exposes a gRPC URL through which + metadata from the backend metastores are served at query time. + + The Dataproc Metastore Federation API defines the following resource + model: + + - The service works with a collection of Google Cloud projects. + - Each project has a collection of available locations. + - Each location has a collection of federations. + - Dataproc Metastore Federations are resources with names of the + form: + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + """ + + _client: DataprocMetastoreFederationClient + + DEFAULT_ENDPOINT = DataprocMetastoreFederationClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DataprocMetastoreFederationClient.DEFAULT_MTLS_ENDPOINT + + federation_path = staticmethod(DataprocMetastoreFederationClient.federation_path) + parse_federation_path = staticmethod(DataprocMetastoreFederationClient.parse_federation_path) + common_billing_account_path = staticmethod(DataprocMetastoreFederationClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DataprocMetastoreFederationClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DataprocMetastoreFederationClient.common_folder_path) + parse_common_folder_path = staticmethod(DataprocMetastoreFederationClient.parse_common_folder_path) + common_organization_path = staticmethod(DataprocMetastoreFederationClient.common_organization_path) + parse_common_organization_path = staticmethod(DataprocMetastoreFederationClient.parse_common_organization_path) + common_project_path = staticmethod(DataprocMetastoreFederationClient.common_project_path) + parse_common_project_path = staticmethod(DataprocMetastoreFederationClient.parse_common_project_path) + common_location_path = staticmethod(DataprocMetastoreFederationClient.common_location_path) + parse_common_location_path = staticmethod(DataprocMetastoreFederationClient.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: + DataprocMetastoreFederationAsyncClient: The constructed client. + """ + return DataprocMetastoreFederationClient.from_service_account_info.__func__(DataprocMetastoreFederationAsyncClient, 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: + DataprocMetastoreFederationAsyncClient: The constructed client. + """ + return DataprocMetastoreFederationClient.from_service_account_file.__func__(DataprocMetastoreFederationAsyncClient, 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 DataprocMetastoreFederationClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DataprocMetastoreFederationTransport: + """Returns the transport used by the client instance. + + Returns: + DataprocMetastoreFederationTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DataprocMetastoreFederationClient).get_transport_class, type(DataprocMetastoreFederationClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DataprocMetastoreFederationTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dataproc metastore federation 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, ~.DataprocMetastoreFederationTransport]): 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 = DataprocMetastoreFederationClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_federations(self, + request: Optional[Union[metastore_federation.ListFederationsRequest, 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.ListFederationsAsyncPager: + r"""Lists federations in a 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 metastore_v1alpha + + async def sample_list_federations(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ListFederationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_federations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.ListFederationsRequest, dict]]): + The request object. Request message for ListFederations. + parent (:class:`str`): + Required. The relative resource name of the location of + metastore federations to list, in the following form: + ``projects/{project_number}/locations/{location_id}``. + + 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.metastore_v1alpha.services.dataproc_metastore_federation.pagers.ListFederationsAsyncPager: + Response message for ListFederations + 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 = metastore_federation.ListFederationsRequest(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_federations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListFederationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_federation(self, + request: Optional[Union[metastore_federation.GetFederationRequest, 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]] = (), + ) -> metastore_federation.Federation: + r"""Gets the details of a single federation. + + .. 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 metastore_v1alpha + + async def sample_get_federation(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.GetFederationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_federation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.GetFederationRequest, dict]]): + The request object. Request message for GetFederation. + name (:class:`str`): + Required. The relative resource name of the metastore + federation to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + 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.metastore_v1alpha.types.Federation: + Represents a federation of multiple + backend metastores. + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 = metastore_federation.GetFederationRequest(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_federation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_federation(self, + request: Optional[Union[metastore_federation.CreateFederationRequest, dict]] = None, + *, + parent: Optional[str] = None, + federation: Optional[metastore_federation.Federation] = None, + federation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a metastore federation in a 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 metastore_v1alpha + + async def sample_create_federation(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.CreateFederationRequest( + parent="parent_value", + federation_id="federation_id_value", + ) + + # Make the request + operation = client.create_federation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.CreateFederationRequest, dict]]): + The request object. Request message for CreateFederation. + parent (:class:`str`): + Required. The relative resource name of the location in + which to create a federation service, in the following + form: + + ``projects/{project_number}/locations/{location_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + federation (:class:`google.cloud.metastore_v1alpha.types.Federation`): + Required. The Metastore Federation to create. The + ``name`` field is ignored. The ID of the created + metastore federation must be provided in the request's + ``federation_id`` field. + + This corresponds to the ``federation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + federation_id (:class:`str`): + Required. The ID of the metastore + federation, which is used as the final + component of the metastore federation's + name. + This value must be between 2 and 63 + characters long inclusive, begin with a + letter, end with a letter or number, and + consist of alpha-numeric ASCII + characters or hyphens. + + This corresponds to the ``federation_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1alpha.types.Federation` + Represents a federation of multiple backend metastores. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, federation, federation_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = metastore_federation.CreateFederationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if federation is not None: + request.federation = federation + if federation_id is not None: + request.federation_id = federation_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_federation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore_federation.Federation, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_federation(self, + request: Optional[Union[metastore_federation.UpdateFederationRequest, dict]] = None, + *, + federation: Optional[metastore_federation.Federation] = 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the fields of a federation. + + .. 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 metastore_v1alpha + + async def sample_update_federation(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.UpdateFederationRequest( + ) + + # Make the request + operation = client.update_federation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.UpdateFederationRequest, dict]]): + The request object. Request message for UpdateFederation. + federation (:class:`google.cloud.metastore_v1alpha.types.Federation`): + Required. The metastore federation to update. The server + only merges fields in the service if they are specified + in ``update_mask``. + + The metastore federation's ``name`` field is used to + identify the metastore service to be updated. + + This corresponds to the ``federation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. A field mask used to specify the fields to be + overwritten in the metastore federation resource by the + update. Fields specified in the ``update_mask`` are + relative to the resource (not to the full request). A + field is overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1alpha.types.Federation` + Represents a federation of multiple backend metastores. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([federation, 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 = metastore_federation.UpdateFederationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if federation is not None: + request.federation = federation + 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_federation, + 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(( + ("federation.name", request.federation.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore_federation.Federation, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_federation(self, + request: Optional[Union[metastore_federation.DeleteFederationRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single federation. + + .. 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 metastore_v1alpha + + async def sample_delete_federation(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.DeleteFederationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_federation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1alpha.types.DeleteFederationRequest, dict]]): + The request object. Request message for DeleteFederation. + name (:class:`str`): + Required. The relative resource name of the metastore + federation to delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 = metastore_federation.DeleteFederationRequest(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_federation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=metastore.OperationMetadata, + ) + + # 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.set_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.GetIamPolicyRequest(**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_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.test_iam_permissions, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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): + 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__ = ( + "DataprocMetastoreFederationAsyncClient", +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/client.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/client.py new file mode 100644 index 0000000..c12ec8c --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/client.py @@ -0,0 +1,1587 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.metastore_v1alpha import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1alpha.services.dataproc_metastore_federation import pagers +from google.cloud.metastore_v1alpha.types import metastore +from google.cloud.metastore_v1alpha.types import metastore_federation +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DataprocMetastoreFederationTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DataprocMetastoreFederationGrpcTransport +from .transports.grpc_asyncio import DataprocMetastoreFederationGrpcAsyncIOTransport +from .transports.rest import DataprocMetastoreFederationRestTransport + + +class DataprocMetastoreFederationClientMeta(type): + """Metaclass for the DataprocMetastoreFederation 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[DataprocMetastoreFederationTransport]] + _transport_registry["grpc"] = DataprocMetastoreFederationGrpcTransport + _transport_registry["grpc_asyncio"] = DataprocMetastoreFederationGrpcAsyncIOTransport + _transport_registry["rest"] = DataprocMetastoreFederationRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[DataprocMetastoreFederationTransport]: + """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 DataprocMetastoreFederationClient(metaclass=DataprocMetastoreFederationClientMeta): + """Configures and manages metastore federation services. Dataproc + Metastore Federation Service allows federating a collection of + backend metastores like BigQuery, Dataplex Lakes, and other Dataproc + Metastores. The Federation Service exposes a gRPC URL through which + metadata from the backend metastores are served at query time. + + The Dataproc Metastore Federation API defines the following resource + model: + + - The service works with a collection of Google Cloud projects. + - Each project has a collection of available locations. + - Each location has a collection of federations. + - Dataproc Metastore Federations are resources with names of the + form: + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + """ + + @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 = "metastore.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: + DataprocMetastoreFederationClient: 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: + DataprocMetastoreFederationClient: 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) -> DataprocMetastoreFederationTransport: + """Returns the transport used by the client instance. + + Returns: + DataprocMetastoreFederationTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def federation_path(project: str,location: str,federation: str,) -> str: + """Returns a fully-qualified federation string.""" + return "projects/{project}/locations/{location}/federations/{federation}".format(project=project, location=location, federation=federation, ) + + @staticmethod + def parse_federation_path(path: str) -> Dict[str,str]: + """Parses a federation path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/federations/(?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, DataprocMetastoreFederationTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dataproc metastore federation 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, DataprocMetastoreFederationTransport]): 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, DataprocMetastoreFederationTransport): + # transport is a DataprocMetastoreFederationTransport 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_federations(self, + request: Optional[Union[metastore_federation.ListFederationsRequest, 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.ListFederationsPager: + r"""Lists federations in a 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 metastore_v1alpha + + def sample_list_federations(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ListFederationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_federations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.ListFederationsRequest, dict]): + The request object. Request message for ListFederations. + parent (str): + Required. The relative resource name of the location of + metastore federations to list, in the following form: + ``projects/{project_number}/locations/{location_id}``. + + 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.metastore_v1alpha.services.dataproc_metastore_federation.pagers.ListFederationsPager: + Response message for ListFederations + 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 metastore_federation.ListFederationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore_federation.ListFederationsRequest): + request = metastore_federation.ListFederationsRequest(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_federations] + + # Certain 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.ListFederationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_federation(self, + request: Optional[Union[metastore_federation.GetFederationRequest, 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]] = (), + ) -> metastore_federation.Federation: + r"""Gets the details of a single federation. + + .. 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 metastore_v1alpha + + def sample_get_federation(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1alpha.GetFederationRequest( + name="name_value", + ) + + # Make the request + response = client.get_federation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.GetFederationRequest, dict]): + The request object. Request message for GetFederation. + name (str): + Required. The relative resource name of the metastore + federation to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + 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.metastore_v1alpha.types.Federation: + Represents a federation of multiple + backend metastores. + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 metastore_federation.GetFederationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore_federation.GetFederationRequest): + request = metastore_federation.GetFederationRequest(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_federation] + + # Certain 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_federation(self, + request: Optional[Union[metastore_federation.CreateFederationRequest, dict]] = None, + *, + parent: Optional[str] = None, + federation: Optional[metastore_federation.Federation] = None, + federation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a metastore federation in a 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 metastore_v1alpha + + def sample_create_federation(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1alpha.CreateFederationRequest( + parent="parent_value", + federation_id="federation_id_value", + ) + + # Make the request + operation = client.create_federation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.CreateFederationRequest, dict]): + The request object. Request message for CreateFederation. + parent (str): + Required. The relative resource name of the location in + which to create a federation service, in the following + form: + + ``projects/{project_number}/locations/{location_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + federation (google.cloud.metastore_v1alpha.types.Federation): + Required. The Metastore Federation to create. The + ``name`` field is ignored. The ID of the created + metastore federation must be provided in the request's + ``federation_id`` field. + + This corresponds to the ``federation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + federation_id (str): + Required. The ID of the metastore + federation, which is used as the final + component of the metastore federation's + name. + This value must be between 2 and 63 + characters long inclusive, begin with a + letter, end with a letter or number, and + consist of alpha-numeric ASCII + characters or hyphens. + + This corresponds to the ``federation_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1alpha.types.Federation` + Represents a federation of multiple backend metastores. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, federation, federation_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a metastore_federation.CreateFederationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore_federation.CreateFederationRequest): + request = metastore_federation.CreateFederationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if federation is not None: + request.federation = federation + if federation_id is not None: + request.federation_id = federation_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_federation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore_federation.Federation, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_federation(self, + request: Optional[Union[metastore_federation.UpdateFederationRequest, dict]] = None, + *, + federation: Optional[metastore_federation.Federation] = 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]] = (), + ) -> operation.Operation: + r"""Updates the fields of a federation. + + .. 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 metastore_v1alpha + + def sample_update_federation(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1alpha.UpdateFederationRequest( + ) + + # Make the request + operation = client.update_federation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.UpdateFederationRequest, dict]): + The request object. Request message for UpdateFederation. + federation (google.cloud.metastore_v1alpha.types.Federation): + Required. The metastore federation to update. The server + only merges fields in the service if they are specified + in ``update_mask``. + + The metastore federation's ``name`` field is used to + identify the metastore service to be updated. + + This corresponds to the ``federation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask used to specify the fields to be + overwritten in the metastore federation resource by the + update. Fields specified in the ``update_mask`` are + relative to the resource (not to the full request). A + field is overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1alpha.types.Federation` + Represents a federation of multiple backend metastores. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([federation, 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 metastore_federation.UpdateFederationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore_federation.UpdateFederationRequest): + request = metastore_federation.UpdateFederationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if federation is not None: + request.federation = federation + 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_federation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("federation.name", request.federation.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore_federation.Federation, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_federation(self, + request: Optional[Union[metastore_federation.DeleteFederationRequest, 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]] = (), + ) -> operation.Operation: + r"""Deletes a single federation. + + .. 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 metastore_v1alpha + + def sample_delete_federation(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1alpha.DeleteFederationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_federation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1alpha.types.DeleteFederationRequest, dict]): + The request object. Request message for DeleteFederation. + name (str): + Required. The relative resource name of the metastore + federation to delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 metastore_federation.DeleteFederationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore_federation.DeleteFederationRequest): + request = metastore_federation.DeleteFederationRequest(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_federation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "DataprocMetastoreFederationClient": + 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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__ = ( + "DataprocMetastoreFederationClient", +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/pagers.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/pagers.py new file mode 100644 index 0000000..0e12a10 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.metastore_v1alpha.types import metastore_federation + + +class ListFederationsPager: + """A pager for iterating through ``list_federations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1alpha.types.ListFederationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``federations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFederations`` requests and continue to iterate + through the ``federations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1alpha.types.ListFederationsResponse` + 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[..., metastore_federation.ListFederationsResponse], + request: metastore_federation.ListFederationsRequest, + response: metastore_federation.ListFederationsResponse, + *, + 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.metastore_v1alpha.types.ListFederationsRequest): + The initial request object. + response (google.cloud.metastore_v1alpha.types.ListFederationsResponse): + 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 = metastore_federation.ListFederationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[metastore_federation.ListFederationsResponse]: + 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[metastore_federation.Federation]: + for page in self.pages: + yield from page.federations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFederationsAsyncPager: + """A pager for iterating through ``list_federations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1alpha.types.ListFederationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``federations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFederations`` requests and continue to iterate + through the ``federations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1alpha.types.ListFederationsResponse` + 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[metastore_federation.ListFederationsResponse]], + request: metastore_federation.ListFederationsRequest, + response: metastore_federation.ListFederationsResponse, + *, + 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.metastore_v1alpha.types.ListFederationsRequest): + The initial request object. + response (google.cloud.metastore_v1alpha.types.ListFederationsResponse): + 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 = metastore_federation.ListFederationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[metastore_federation.ListFederationsResponse]: + 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[metastore_federation.Federation]: + async def async_generator(): + async for page in self.pages: + for response in page.federations: + 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/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/__init__.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/__init__.py new file mode 100644 index 0000000..0ba9a1b --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import DataprocMetastoreFederationTransport +from .grpc import DataprocMetastoreFederationGrpcTransport +from .grpc_asyncio import DataprocMetastoreFederationGrpcAsyncIOTransport +from .rest import DataprocMetastoreFederationRestTransport +from .rest import DataprocMetastoreFederationRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DataprocMetastoreFederationTransport]] +_transport_registry['grpc'] = DataprocMetastoreFederationGrpcTransport +_transport_registry['grpc_asyncio'] = DataprocMetastoreFederationGrpcAsyncIOTransport +_transport_registry['rest'] = DataprocMetastoreFederationRestTransport + +__all__ = ( + 'DataprocMetastoreFederationTransport', + 'DataprocMetastoreFederationGrpcTransport', + 'DataprocMetastoreFederationGrpcAsyncIOTransport', + 'DataprocMetastoreFederationRestTransport', + 'DataprocMetastoreFederationRestInterceptor', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/base.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/base.py new file mode 100644 index 0000000..9c936e8 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/base.py @@ -0,0 +1,288 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.metastore_v1alpha import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1alpha.types import metastore_federation +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class DataprocMetastoreFederationTransport(abc.ABC): + """Abstract transport class for DataprocMetastoreFederation.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'metastore.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_federations: gapic_v1.method.wrap_method( + self.list_federations, + default_timeout=None, + client_info=client_info, + ), + self.get_federation: gapic_v1.method.wrap_method( + self.get_federation, + default_timeout=None, + client_info=client_info, + ), + self.create_federation: gapic_v1.method.wrap_method( + self.create_federation, + default_timeout=None, + client_info=client_info, + ), + self.update_federation: gapic_v1.method.wrap_method( + self.update_federation, + default_timeout=None, + client_info=client_info, + ), + self.delete_federation: gapic_v1.method.wrap_method( + self.delete_federation, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_federations(self) -> Callable[ + [metastore_federation.ListFederationsRequest], + Union[ + metastore_federation.ListFederationsResponse, + Awaitable[metastore_federation.ListFederationsResponse] + ]]: + raise NotImplementedError() + + @property + def get_federation(self) -> Callable[ + [metastore_federation.GetFederationRequest], + Union[ + metastore_federation.Federation, + Awaitable[metastore_federation.Federation] + ]]: + raise NotImplementedError() + + @property + def create_federation(self) -> Callable[ + [metastore_federation.CreateFederationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_federation(self) -> Callable[ + [metastore_federation.UpdateFederationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_federation(self) -> Callable[ + [metastore_federation.DeleteFederationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + 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 delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + 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__ = ( + 'DataprocMetastoreFederationTransport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/grpc.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/grpc.py new file mode 100644 index 0000000..3a7c371 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/grpc.py @@ -0,0 +1,575 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1alpha.types import metastore_federation +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from .base import DataprocMetastoreFederationTransport, DEFAULT_CLIENT_INFO + + +class DataprocMetastoreFederationGrpcTransport(DataprocMetastoreFederationTransport): + """gRPC backend transport for DataprocMetastoreFederation. + + Configures and manages metastore federation services. Dataproc + Metastore Federation Service allows federating a collection of + backend metastores like BigQuery, Dataplex Lakes, and other Dataproc + Metastores. The Federation Service exposes a gRPC URL through which + metadata from the backend metastores are served at query time. + + The Dataproc Metastore Federation API defines the following resource + model: + + - The service works with a collection of Google Cloud projects. + - Each project has a collection of available locations. + - Each location has a collection of federations. + - Dataproc Metastore Federations are resources with names of the + form: + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + 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 = 'metastore.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] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + 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 = 'metastore.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 operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_federations(self) -> Callable[ + [metastore_federation.ListFederationsRequest], + metastore_federation.ListFederationsResponse]: + r"""Return a callable for the list federations method over gRPC. + + Lists federations in a project and location. + + Returns: + Callable[[~.ListFederationsRequest], + ~.ListFederationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_federations' not in self._stubs: + self._stubs['list_federations'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastoreFederation/ListFederations', + request_serializer=metastore_federation.ListFederationsRequest.serialize, + response_deserializer=metastore_federation.ListFederationsResponse.deserialize, + ) + return self._stubs['list_federations'] + + @property + def get_federation(self) -> Callable[ + [metastore_federation.GetFederationRequest], + metastore_federation.Federation]: + r"""Return a callable for the get federation method over gRPC. + + Gets the details of a single federation. + + Returns: + Callable[[~.GetFederationRequest], + ~.Federation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_federation' not in self._stubs: + self._stubs['get_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastoreFederation/GetFederation', + request_serializer=metastore_federation.GetFederationRequest.serialize, + response_deserializer=metastore_federation.Federation.deserialize, + ) + return self._stubs['get_federation'] + + @property + def create_federation(self) -> Callable[ + [metastore_federation.CreateFederationRequest], + operations_pb2.Operation]: + r"""Return a callable for the create federation method over gRPC. + + Creates a metastore federation in a project and + location. + + Returns: + Callable[[~.CreateFederationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_federation' not in self._stubs: + self._stubs['create_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastoreFederation/CreateFederation', + request_serializer=metastore_federation.CreateFederationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_federation'] + + @property + def update_federation(self) -> Callable[ + [metastore_federation.UpdateFederationRequest], + operations_pb2.Operation]: + r"""Return a callable for the update federation method over gRPC. + + Updates the fields of a federation. + + Returns: + Callable[[~.UpdateFederationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_federation' not in self._stubs: + self._stubs['update_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastoreFederation/UpdateFederation', + request_serializer=metastore_federation.UpdateFederationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_federation'] + + @property + def delete_federation(self) -> Callable[ + [metastore_federation.DeleteFederationRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete federation method over gRPC. + + Deletes a single federation. + + Returns: + Callable[[~.DeleteFederationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_federation' not in self._stubs: + self._stubs['delete_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastoreFederation/DeleteFederation', + request_serializer=metastore_federation.DeleteFederationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_federation'] + + 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 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 set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'DataprocMetastoreFederationGrpcTransport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/grpc_asyncio.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/grpc_asyncio.py new file mode 100644 index 0000000..8f7e9db --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/grpc_asyncio.py @@ -0,0 +1,574 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1alpha.types import metastore_federation +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from .base import DataprocMetastoreFederationTransport, DEFAULT_CLIENT_INFO +from .grpc import DataprocMetastoreFederationGrpcTransport + + +class DataprocMetastoreFederationGrpcAsyncIOTransport(DataprocMetastoreFederationTransport): + """gRPC AsyncIO backend transport for DataprocMetastoreFederation. + + Configures and manages metastore federation services. Dataproc + Metastore Federation Service allows federating a collection of + backend metastores like BigQuery, Dataplex Lakes, and other Dataproc + Metastores. The Federation Service exposes a gRPC URL through which + metadata from the backend metastores are served at query time. + + The Dataproc Metastore Federation API defines the following resource + model: + + - The service works with a collection of Google Cloud projects. + - Each project has a collection of available locations. + - Each location has a collection of federations. + - Dataproc Metastore Federations are resources with names of the + form: + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + 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 = 'metastore.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 = 'metastore.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] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + 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 operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_federations(self) -> Callable[ + [metastore_federation.ListFederationsRequest], + Awaitable[metastore_federation.ListFederationsResponse]]: + r"""Return a callable for the list federations method over gRPC. + + Lists federations in a project and location. + + Returns: + Callable[[~.ListFederationsRequest], + Awaitable[~.ListFederationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_federations' not in self._stubs: + self._stubs['list_federations'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastoreFederation/ListFederations', + request_serializer=metastore_federation.ListFederationsRequest.serialize, + response_deserializer=metastore_federation.ListFederationsResponse.deserialize, + ) + return self._stubs['list_federations'] + + @property + def get_federation(self) -> Callable[ + [metastore_federation.GetFederationRequest], + Awaitable[metastore_federation.Federation]]: + r"""Return a callable for the get federation method over gRPC. + + Gets the details of a single federation. + + Returns: + Callable[[~.GetFederationRequest], + Awaitable[~.Federation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_federation' not in self._stubs: + self._stubs['get_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastoreFederation/GetFederation', + request_serializer=metastore_federation.GetFederationRequest.serialize, + response_deserializer=metastore_federation.Federation.deserialize, + ) + return self._stubs['get_federation'] + + @property + def create_federation(self) -> Callable[ + [metastore_federation.CreateFederationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create federation method over gRPC. + + Creates a metastore federation in a project and + location. + + Returns: + Callable[[~.CreateFederationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_federation' not in self._stubs: + self._stubs['create_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastoreFederation/CreateFederation', + request_serializer=metastore_federation.CreateFederationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_federation'] + + @property + def update_federation(self) -> Callable[ + [metastore_federation.UpdateFederationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update federation method over gRPC. + + Updates the fields of a federation. + + Returns: + Callable[[~.UpdateFederationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_federation' not in self._stubs: + self._stubs['update_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastoreFederation/UpdateFederation', + request_serializer=metastore_federation.UpdateFederationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_federation'] + + @property + def delete_federation(self) -> Callable[ + [metastore_federation.DeleteFederationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete federation method over gRPC. + + Deletes a single federation. + + Returns: + Callable[[~.DeleteFederationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_federation' not in self._stubs: + self._stubs['delete_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1alpha.DataprocMetastoreFederation/DeleteFederation', + request_serializer=metastore_federation.DeleteFederationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_federation'] + + 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 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 set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'DataprocMetastoreFederationGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/rest.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/rest.py new file mode 100644 index 0000000..ee3359b --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/rest.py @@ -0,0 +1,1552 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +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.metastore_v1alpha.types import metastore_federation +from google.longrunning import operations_pb2 # type: ignore + +from .base import DataprocMetastoreFederationTransport, 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 DataprocMetastoreFederationRestInterceptor: + """Interceptor for DataprocMetastoreFederation. + + 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 DataprocMetastoreFederationRestTransport. + + .. code-block:: python + class MyCustomDataprocMetastoreFederationInterceptor(DataprocMetastoreFederationRestInterceptor): + def pre_create_federation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_federation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_federation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_federation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_federation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_federation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_federations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_federations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_federation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_federation(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DataprocMetastoreFederationRestTransport(interceptor=MyCustomDataprocMetastoreFederationInterceptor()) + client = DataprocMetastoreFederationClient(transport=transport) + + + """ + def pre_create_federation(self, request: metastore_federation.CreateFederationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore_federation.CreateFederationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_federation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_create_federation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_federation + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_delete_federation(self, request: metastore_federation.DeleteFederationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore_federation.DeleteFederationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_federation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_delete_federation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_federation + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_get_federation(self, request: metastore_federation.GetFederationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore_federation.GetFederationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_federation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_get_federation(self, response: metastore_federation.Federation) -> metastore_federation.Federation: + """Post-rpc interceptor for get_federation + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_list_federations(self, request: metastore_federation.ListFederationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore_federation.ListFederationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_federations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_list_federations(self, response: metastore_federation.ListFederationsResponse) -> metastore_federation.ListFederationsResponse: + """Post-rpc interceptor for list_federations + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_update_federation(self, request: metastore_federation.UpdateFederationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore_federation.UpdateFederationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_federation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_update_federation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_federation + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DataprocMetastoreFederationRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DataprocMetastoreFederationRestInterceptor + + +class DataprocMetastoreFederationRestTransport(DataprocMetastoreFederationTransport): + """REST backend transport for DataprocMetastoreFederation. + + Configures and manages metastore federation services. Dataproc + Metastore Federation Service allows federating a collection of + backend metastores like BigQuery, Dataplex Lakes, and other Dataproc + Metastores. The Federation Service exposes a gRPC URL through which + metadata from the backend metastores are served at query time. + + The Dataproc Metastore Federation API defines the following resource + model: + + - The service works with a collection of Google Cloud projects. + - Each project has a collection of available locations. + - Each location has a collection of federations. + - Dataproc Metastore Federations are resources with names of the + form: + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + 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 = 'metastore.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[DataprocMetastoreFederationRestInterceptor] = 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) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DataprocMetastoreFederationRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1alpha") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateFederation(DataprocMetastoreFederationRestStub): + def __hash__(self): + return hash("CreateFederation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "federationId" : "", } + + @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: metastore_federation.CreateFederationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create federation method over HTTP. + + Args: + request (~.metastore_federation.CreateFederationRequest): + The request object. Request message for CreateFederation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*}/federations', + 'body': 'federation', + }, + ] + request, metadata = self._interceptor.pre_create_federation(request, metadata) + pb_request = metastore_federation.CreateFederationRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_federation(resp) + return resp + + class _DeleteFederation(DataprocMetastoreFederationRestStub): + def __hash__(self): + return hash("DeleteFederation") + + __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: metastore_federation.DeleteFederationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete federation method over HTTP. + + Args: + request (~.metastore_federation.DeleteFederationRequest): + The request object. Request message for DeleteFederation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha/{name=projects/*/locations/*/federations/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_federation(request, metadata) + pb_request = metastore_federation.DeleteFederationRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_federation(resp) + return resp + + class _GetFederation(DataprocMetastoreFederationRestStub): + def __hash__(self): + return hash("GetFederation") + + __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: metastore_federation.GetFederationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore_federation.Federation: + r"""Call the get federation method over HTTP. + + Args: + request (~.metastore_federation.GetFederationRequest): + The request object. Request message for GetFederation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore_federation.Federation: + Represents a federation of multiple + backend metastores. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/federations/*}', + }, + ] + request, metadata = self._interceptor.pre_get_federation(request, metadata) + pb_request = metastore_federation.GetFederationRequest.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 = metastore_federation.Federation() + pb_resp = metastore_federation.Federation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_federation(resp) + return resp + + class _ListFederations(DataprocMetastoreFederationRestStub): + def __hash__(self): + return hash("ListFederations") + + __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: metastore_federation.ListFederationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore_federation.ListFederationsResponse: + r"""Call the list federations method over HTTP. + + Args: + request (~.metastore_federation.ListFederationsRequest): + The request object. Request message for ListFederations. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore_federation.ListFederationsResponse: + Response message for ListFederations + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*}/federations', + }, + ] + request, metadata = self._interceptor.pre_list_federations(request, metadata) + pb_request = metastore_federation.ListFederationsRequest.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 = metastore_federation.ListFederationsResponse() + pb_resp = metastore_federation.ListFederationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_federations(resp) + return resp + + class _UpdateFederation(DataprocMetastoreFederationRestStub): + def __hash__(self): + return hash("UpdateFederation") + + __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: metastore_federation.UpdateFederationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update federation method over HTTP. + + Args: + request (~.metastore_federation.UpdateFederationRequest): + The request object. Request message for UpdateFederation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{federation.name=projects/*/locations/*/federations/*}', + 'body': 'federation', + }, + ] + request, metadata = self._interceptor.pre_update_federation(request, metadata) + pb_request = metastore_federation.UpdateFederationRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_federation(resp) + return resp + + @property + def create_federation(self) -> Callable[ + [metastore_federation.CreateFederationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateFederation(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_federation(self) -> Callable[ + [metastore_federation.DeleteFederationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteFederation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_federation(self) -> Callable[ + [metastore_federation.GetFederationRequest], + metastore_federation.Federation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetFederation(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_federations(self) -> Callable[ + [metastore_federation.ListFederationsRequest], + metastore_federation.ListFederationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListFederations(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_federation(self) -> Callable[ + [metastore_federation.UpdateFederationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateFederation(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(DataprocMetastoreFederationRestStub): + 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': '/v1alpha/{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(DataprocMetastoreFederationRestStub): + 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': '/v1alpha/{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 get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(DataprocMetastoreFederationRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy 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: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/backups/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/databases/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/databases/*/tables/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{resource=projects/*/locations/*/federations/*}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(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 = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(DataprocMetastoreFederationRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy 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: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/backups/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/databases/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/databases/*/tables/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/federations/*}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.loads(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) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(DataprocMetastoreFederationRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions 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: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/backups/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/databases/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/services/*/databases/*/tables/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{resource=projects/*/locations/*/federations/*}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.loads(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) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(DataprocMetastoreFederationRestStub): + 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': '/v1alpha/{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(DataprocMetastoreFederationRestStub): + 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': '/v1alpha/{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(DataprocMetastoreFederationRestStub): + 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': '/v1alpha/{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__=( + 'DataprocMetastoreFederationRestTransport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/types/__init__.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/types/__init__.py new file mode 100644 index 0000000..12c86eb --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/types/__init__.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .metastore import ( + AlterMetadataResourceLocationRequest, + AlterMetadataResourceLocationResponse, + AuxiliaryVersionConfig, + Backup, + CreateBackupRequest, + CreateMetadataImportRequest, + CreateServiceRequest, + DatabaseDumpSpec, + DataCatalogConfig, + DataplexConfig, + DeleteBackupRequest, + DeleteServiceRequest, + EncryptionConfig, + ExportMetadataRequest, + GetBackupRequest, + GetMetadataImportRequest, + GetServiceRequest, + HiveMetastoreConfig, + KerberosConfig, + Lake, + ListBackupsRequest, + ListBackupsResponse, + ListMetadataImportsRequest, + ListMetadataImportsResponse, + ListServicesRequest, + ListServicesResponse, + LocationMetadata, + MaintenanceWindow, + MetadataExport, + MetadataImport, + MetadataIntegration, + MetadataManagementActivity, + MoveTableToDatabaseRequest, + MoveTableToDatabaseResponse, + NetworkConfig, + OperationMetadata, + QueryMetadataRequest, + QueryMetadataResponse, + RemoveIamPolicyRequest, + RemoveIamPolicyResponse, + Restore, + RestoreServiceRequest, + Secret, + Service, + TelemetryConfig, + UpdateMetadataImportRequest, + UpdateServiceRequest, +) +from .metastore_federation import ( + BackendMetastore, + CreateFederationRequest, + DeleteFederationRequest, + Federation, + GetFederationRequest, + ListFederationsRequest, + ListFederationsResponse, + UpdateFederationRequest, +) + +__all__ = ( + 'AlterMetadataResourceLocationRequest', + 'AlterMetadataResourceLocationResponse', + 'AuxiliaryVersionConfig', + 'Backup', + 'CreateBackupRequest', + 'CreateMetadataImportRequest', + 'CreateServiceRequest', + 'DatabaseDumpSpec', + 'DataCatalogConfig', + 'DataplexConfig', + 'DeleteBackupRequest', + 'DeleteServiceRequest', + 'EncryptionConfig', + 'ExportMetadataRequest', + 'GetBackupRequest', + 'GetMetadataImportRequest', + 'GetServiceRequest', + 'HiveMetastoreConfig', + 'KerberosConfig', + 'Lake', + 'ListBackupsRequest', + 'ListBackupsResponse', + 'ListMetadataImportsRequest', + 'ListMetadataImportsResponse', + 'ListServicesRequest', + 'ListServicesResponse', + 'LocationMetadata', + 'MaintenanceWindow', + 'MetadataExport', + 'MetadataImport', + 'MetadataIntegration', + 'MetadataManagementActivity', + 'MoveTableToDatabaseRequest', + 'MoveTableToDatabaseResponse', + 'NetworkConfig', + 'OperationMetadata', + 'QueryMetadataRequest', + 'QueryMetadataResponse', + 'RemoveIamPolicyRequest', + 'RemoveIamPolicyResponse', + 'Restore', + 'RestoreServiceRequest', + 'Secret', + 'Service', + 'TelemetryConfig', + 'UpdateMetadataImportRequest', + 'UpdateServiceRequest', + 'BackendMetastore', + 'CreateFederationRequest', + 'DeleteFederationRequest', + 'Federation', + 'GetFederationRequest', + 'ListFederationsRequest', + 'ListFederationsResponse', + 'UpdateFederationRequest', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/types/metastore.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/types/metastore.py new file mode 100644 index 0000000..4cb72cb --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/types/metastore.py @@ -0,0 +1,2257 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __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.protobuf import wrappers_pb2 # type: ignore +from google.type import dayofweek_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.metastore.v1alpha', + manifest={ + 'Service', + 'MetadataIntegration', + 'DataCatalogConfig', + 'DataplexConfig', + 'Lake', + 'MaintenanceWindow', + 'HiveMetastoreConfig', + 'KerberosConfig', + 'Secret', + 'EncryptionConfig', + 'AuxiliaryVersionConfig', + 'NetworkConfig', + 'TelemetryConfig', + 'MetadataManagementActivity', + 'MetadataImport', + 'MetadataExport', + 'Backup', + 'Restore', + 'ListServicesRequest', + 'ListServicesResponse', + 'GetServiceRequest', + 'CreateServiceRequest', + 'UpdateServiceRequest', + 'DeleteServiceRequest', + 'ListMetadataImportsRequest', + 'ListMetadataImportsResponse', + 'GetMetadataImportRequest', + 'CreateMetadataImportRequest', + 'UpdateMetadataImportRequest', + 'ListBackupsRequest', + 'ListBackupsResponse', + 'GetBackupRequest', + 'CreateBackupRequest', + 'DeleteBackupRequest', + 'ExportMetadataRequest', + 'RestoreServiceRequest', + 'OperationMetadata', + 'LocationMetadata', + 'DatabaseDumpSpec', + 'RemoveIamPolicyRequest', + 'RemoveIamPolicyResponse', + 'QueryMetadataRequest', + 'QueryMetadataResponse', + 'MoveTableToDatabaseRequest', + 'MoveTableToDatabaseResponse', + 'AlterMetadataResourceLocationRequest', + 'AlterMetadataResourceLocationResponse', + }, +) + + +class Service(proto.Message): + r"""A managed metastore service that serves metadata queries. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + hive_metastore_config (google.cloud.metastore_v1alpha.types.HiveMetastoreConfig): + Configuration information specific to running + Hive metastore software as the metastore + service. + + This field is a member of `oneof`_ ``metastore_config``. + name (str): + Immutable. The relative resource name of the metastore + service, in the following format: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metastore + service was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metastore + service was last updated. + labels (MutableMapping[str, str]): + User-defined labels for the metastore + service. + network (str): + Immutable. The relative resource name of the VPC network on + which the instance can be accessed. It is specified in the + following form: + + ``projects/{project_number}/global/networks/{network_id}``. + endpoint_uri (str): + Output only. The URI of the endpoint used to + access the metastore service. + port (int): + The TCP port at which the metastore service + is reached. Default: 9083. + state (google.cloud.metastore_v1alpha.types.Service.State): + Output only. The current state of the + metastore service. + state_message (str): + Output only. Additional information about the + current state of the metastore service, if + available. + artifact_gcs_uri (str): + Output only. A Cloud Storage URI (starting with ``gs://``) + that specifies where artifacts related to the metastore + service are stored. + tier (google.cloud.metastore_v1alpha.types.Service.Tier): + The tier of the service. + metadata_integration (google.cloud.metastore_v1alpha.types.MetadataIntegration): + The setting that defines how metastore + metadata should be integrated with external + services and systems. + maintenance_window (google.cloud.metastore_v1alpha.types.MaintenanceWindow): + The one hour maintenance window of the + metastore service. This specifies when the + service can be restarted for maintenance + purposes in UTC time. Maintenance window is not + needed for services with the SPANNER database + type. + uid (str): + Output only. The globally unique resource + identifier of the metastore service. + metadata_management_activity (google.cloud.metastore_v1alpha.types.MetadataManagementActivity): + Output only. The metadata management + activities of the metastore service. + release_channel (google.cloud.metastore_v1alpha.types.Service.ReleaseChannel): + Immutable. The release channel of the service. If + unspecified, defaults to ``STABLE``. + encryption_config (google.cloud.metastore_v1alpha.types.EncryptionConfig): + Immutable. Information used to configure the + Dataproc Metastore service to encrypt customer + data at rest. Cannot be updated. + network_config (google.cloud.metastore_v1alpha.types.NetworkConfig): + The configuration specifying the network + settings for the Dataproc Metastore service. + database_type (google.cloud.metastore_v1alpha.types.Service.DatabaseType): + Immutable. The database type that the + Metastore service stores its data. + telemetry_config (google.cloud.metastore_v1alpha.types.TelemetryConfig): + The configuration specifying telemetry settings for the + Dataproc Metastore service. If unspecified defaults to + ``JSON``. + """ + class State(proto.Enum): + r"""The current state of the metastore service. + + Values: + STATE_UNSPECIFIED (0): + The state of the metastore service is + unknown. + CREATING (1): + The metastore service is in the process of + being created. + ACTIVE (2): + The metastore service is running and ready to + serve queries. + SUSPENDING (3): + The metastore service is entering suspension. + Its query-serving availability may cease + unexpectedly. + SUSPENDED (4): + The metastore service is suspended and unable + to serve queries. + UPDATING (5): + The metastore service is being updated. It + remains usable but cannot accept additional + update requests or be deleted at this time. + DELETING (6): + The metastore service is undergoing deletion. + It cannot be used. + ERROR (7): + The metastore service has encountered an + error and cannot be used. The metastore service + should be deleted. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + SUSPENDING = 3 + SUSPENDED = 4 + UPDATING = 5 + DELETING = 6 + ERROR = 7 + + class Tier(proto.Enum): + r"""Available service tiers. + + Values: + TIER_UNSPECIFIED (0): + The tier is not set. + DEVELOPER (1): + The developer tier provides limited + scalability and no fault tolerance. Good for + low-cost proof-of-concept. + ENTERPRISE (3): + The enterprise tier provides multi-zone high + availability, and sufficient scalability for + enterprise-level Dataproc Metastore workloads. + """ + TIER_UNSPECIFIED = 0 + DEVELOPER = 1 + ENTERPRISE = 3 + + class ReleaseChannel(proto.Enum): + r"""Release channels bundle features of varying levels of + stability. Newer features may be introduced initially into less + stable release channels and can be automatically promoted into + more stable release channels. + + Values: + RELEASE_CHANNEL_UNSPECIFIED (0): + Release channel is not specified. + CANARY (1): + The ``CANARY`` release channel contains the newest features, + which may be unstable and subject to unresolved issues with + no known workarounds. Services using the ``CANARY`` release + channel are not subject to any SLAs. + STABLE (2): + The ``STABLE`` release channel contains features that are + considered stable and have been validated for production + use. + """ + RELEASE_CHANNEL_UNSPECIFIED = 0 + CANARY = 1 + STABLE = 2 + + class DatabaseType(proto.Enum): + r"""The backend database type for the metastore service. + + Values: + DATABASE_TYPE_UNSPECIFIED (0): + The DATABASE_TYPE is not set. + MYSQL (1): + MySQL is used to persist the metastore data. + SPANNER (2): + Spanner is used to persist the metastore + data. + """ + DATABASE_TYPE_UNSPECIFIED = 0 + MYSQL = 1 + SPANNER = 2 + + hive_metastore_config: 'HiveMetastoreConfig' = proto.Field( + proto.MESSAGE, + number=5, + oneof='metastore_config', + message='HiveMetastoreConfig', + ) + 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, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + network: str = proto.Field( + proto.STRING, + number=7, + ) + endpoint_uri: str = proto.Field( + proto.STRING, + number=8, + ) + port: int = proto.Field( + proto.INT32, + number=9, + ) + state: State = proto.Field( + proto.ENUM, + number=10, + enum=State, + ) + state_message: str = proto.Field( + proto.STRING, + number=11, + ) + artifact_gcs_uri: str = proto.Field( + proto.STRING, + number=12, + ) + tier: Tier = proto.Field( + proto.ENUM, + number=13, + enum=Tier, + ) + metadata_integration: 'MetadataIntegration' = proto.Field( + proto.MESSAGE, + number=14, + message='MetadataIntegration', + ) + maintenance_window: 'MaintenanceWindow' = proto.Field( + proto.MESSAGE, + number=15, + message='MaintenanceWindow', + ) + uid: str = proto.Field( + proto.STRING, + number=16, + ) + metadata_management_activity: 'MetadataManagementActivity' = proto.Field( + proto.MESSAGE, + number=17, + message='MetadataManagementActivity', + ) + release_channel: ReleaseChannel = proto.Field( + proto.ENUM, + number=19, + enum=ReleaseChannel, + ) + encryption_config: 'EncryptionConfig' = proto.Field( + proto.MESSAGE, + number=20, + message='EncryptionConfig', + ) + network_config: 'NetworkConfig' = proto.Field( + proto.MESSAGE, + number=21, + message='NetworkConfig', + ) + database_type: DatabaseType = proto.Field( + proto.ENUM, + number=22, + enum=DatabaseType, + ) + telemetry_config: 'TelemetryConfig' = proto.Field( + proto.MESSAGE, + number=23, + message='TelemetryConfig', + ) + + +class MetadataIntegration(proto.Message): + r"""Specifies how metastore metadata should be integrated with + external services. + + Attributes: + data_catalog_config (google.cloud.metastore_v1alpha.types.DataCatalogConfig): + The integration config for the Data Catalog + service. + dataplex_config (google.cloud.metastore_v1alpha.types.DataplexConfig): + The integration config for the Dataplex + service. + """ + + data_catalog_config: 'DataCatalogConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='DataCatalogConfig', + ) + dataplex_config: 'DataplexConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='DataplexConfig', + ) + + +class DataCatalogConfig(proto.Message): + r"""Specifies how metastore metadata should be integrated with + the Data Catalog service. + + Attributes: + enabled (bool): + Defines whether the metastore metadata should + be synced to Data Catalog. The default value is + to disable syncing metastore metadata to Data + Catalog. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class DataplexConfig(proto.Message): + r"""Specifies how metastore metadata should be integrated with + the Dataplex service. + + Attributes: + lake_resources (MutableMapping[str, google.cloud.metastore_v1alpha.types.Lake]): + A reference to the Lake resources that this metastore + service is attached to. The key is the lake resource name. + Example: + ``projects/{project_number}/locations/{location_id}/lakes/{lake_id}``. + """ + + lake_resources: MutableMapping[str, 'Lake'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message='Lake', + ) + + +class Lake(proto.Message): + r"""Represents a Lake resource + + Attributes: + name (str): + The Lake resource name. Example: + ``projects/{project_number}/locations/{location_id}/lakes/{lake_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class MaintenanceWindow(proto.Message): + r"""Maintenance window. This specifies when Dataproc Metastore + may perform system maintenance operation to the service. + + Attributes: + hour_of_day (google.protobuf.wrappers_pb2.Int32Value): + The hour of day (0-23) when the window + starts. + day_of_week (google.type.dayofweek_pb2.DayOfWeek): + The day of week, when the window starts. + """ + + hour_of_day: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=1, + message=wrappers_pb2.Int32Value, + ) + day_of_week: dayofweek_pb2.DayOfWeek = proto.Field( + proto.ENUM, + number=2, + enum=dayofweek_pb2.DayOfWeek, + ) + + +class HiveMetastoreConfig(proto.Message): + r"""Specifies configuration information specific to running Hive + metastore software as the metastore service. + + Attributes: + version (str): + Immutable. The Hive metastore schema version. + config_overrides (MutableMapping[str, str]): + A mapping of Hive metastore configuration key-value pairs to + apply to the Hive metastore (configured in + ``hive-site.xml``). The mappings override system defaults + (some keys cannot be overridden). These overrides are also + applied to auxiliary versions and can be further customized + in the auxiliary version's ``AuxiliaryVersionConfig``. + kerberos_config (google.cloud.metastore_v1alpha.types.KerberosConfig): + Information used to configure the Hive metastore service as + a service principal in a Kerberos realm. To disable + Kerberos, use the ``UpdateService`` method and specify this + field's path (``hive_metastore_config.kerberos_config``) in + the request's ``update_mask`` while omitting this field from + the request's ``service``. + endpoint_protocol (google.cloud.metastore_v1alpha.types.HiveMetastoreConfig.EndpointProtocol): + The protocol to use for the metastore service endpoint. If + unspecified, defaults to ``THRIFT``. + auxiliary_versions (MutableMapping[str, google.cloud.metastore_v1alpha.types.AuxiliaryVersionConfig]): + A mapping of Hive metastore version to the auxiliary version + configuration. When specified, a secondary Hive metastore + service is created along with the primary service. All + auxiliary versions must be less than the service's primary + version. The key is the auxiliary service name and it must + match the regular expression `a-z <[-a-z0-9]*[a-z0-9]>`__?. + This means that the first character must be a lowercase + letter, and all the following characters must be hyphens, + lowercase letters, or digits, except the last character, + which cannot be a hyphen. + """ + class EndpointProtocol(proto.Enum): + r"""Protocols available for serving the metastore service + endpoint. + + Values: + ENDPOINT_PROTOCOL_UNSPECIFIED (0): + The protocol is not set. + THRIFT (1): + Use the legacy Apache Thrift protocol for the + metastore service endpoint. + GRPC (2): + Use the modernized gRPC protocol for the + metastore service endpoint. + """ + ENDPOINT_PROTOCOL_UNSPECIFIED = 0 + THRIFT = 1 + GRPC = 2 + + version: str = proto.Field( + proto.STRING, + number=1, + ) + config_overrides: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + kerberos_config: 'KerberosConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='KerberosConfig', + ) + endpoint_protocol: EndpointProtocol = proto.Field( + proto.ENUM, + number=4, + enum=EndpointProtocol, + ) + auxiliary_versions: MutableMapping[str, 'AuxiliaryVersionConfig'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=5, + message='AuxiliaryVersionConfig', + ) + + +class KerberosConfig(proto.Message): + r"""Configuration information for a Kerberos principal. + + Attributes: + keytab (google.cloud.metastore_v1alpha.types.Secret): + A Kerberos keytab file that can be used to + authenticate a service principal with a Kerberos + Key Distribution Center (KDC). + principal (str): + A Kerberos principal that exists in the both the keytab the + KDC to authenticate as. A typical principal is of the form + ``primary/instance@REALM``, but there is no exact format. + krb5_config_gcs_uri (str): + A Cloud Storage URI that specifies the path to a krb5.conf + file. It is of the form + ``gs://{bucket_name}/path/to/krb5.conf``, although the file + does not need to be named krb5.conf explicitly. + """ + + keytab: 'Secret' = proto.Field( + proto.MESSAGE, + number=1, + message='Secret', + ) + principal: str = proto.Field( + proto.STRING, + number=2, + ) + krb5_config_gcs_uri: str = proto.Field( + proto.STRING, + number=3, + ) + + +class Secret(proto.Message): + r"""A securely stored value. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_secret (str): + The relative resource name of a Secret Manager secret + version, in the following form: + + ``projects/{project_number}/secrets/{secret_id}/versions/{version_id}``. + + This field is a member of `oneof`_ ``value``. + """ + + cloud_secret: str = proto.Field( + proto.STRING, + number=2, + oneof='value', + ) + + +class EncryptionConfig(proto.Message): + r"""Encryption settings for the service. + + Attributes: + kms_key (str): + The fully qualified customer provided Cloud KMS key name to + use for customer data encryption, in the following form: + + ``projects/{project_number}/locations/{location_id}/keyRings/{key_ring_id}/cryptoKeys/{crypto_key_id}``. + """ + + kms_key: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AuxiliaryVersionConfig(proto.Message): + r"""Configuration information for the auxiliary service versions. + + Attributes: + version (str): + The Hive metastore version of the auxiliary + service. It must be less than the primary Hive + metastore service's version. + config_overrides (MutableMapping[str, str]): + A mapping of Hive metastore configuration key-value pairs to + apply to the auxiliary Hive metastore (configured in + ``hive-site.xml``) in addition to the primary version's + overrides. If keys are present in both the auxiliary + version's overrides and the primary version's overrides, the + value from the auxiliary version's overrides takes + precedence. + network_config (google.cloud.metastore_v1alpha.types.NetworkConfig): + Output only. The network configuration + contains the endpoint URI(s) of the auxiliary + Hive metastore service. + """ + + version: str = proto.Field( + proto.STRING, + number=1, + ) + config_overrides: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + network_config: 'NetworkConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='NetworkConfig', + ) + + +class NetworkConfig(proto.Message): + r"""Network configuration for the Dataproc Metastore service. + + Attributes: + consumers (MutableSequence[google.cloud.metastore_v1alpha.types.NetworkConfig.Consumer]): + Immutable. The consumer-side network + configuration for the Dataproc Metastore + instance. + """ + + class Consumer(proto.Message): + r"""Contains information of the customer's network + configurations. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + subnetwork (str): + Immutable. The subnetwork of the customer project from which + an IP address is reserved and used as the Dataproc Metastore + service's endpoint. It is accessible to hosts in the subnet + and to all hosts in a subnet in the same region and same + network. There must be at least one IP address available in + the subnet's primary range. The subnet is specified in the + following form: + + ``projects/{project_number}/regions/{region_id}/subnetworks/{subnetwork_id}`` + + This field is a member of `oneof`_ ``vpc_resource``. + endpoint_uri (str): + Output only. The URI of the endpoint used to + access the metastore service. + """ + + subnetwork: str = proto.Field( + proto.STRING, + number=1, + oneof='vpc_resource', + ) + endpoint_uri: str = proto.Field( + proto.STRING, + number=3, + ) + + consumers: MutableSequence[Consumer] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Consumer, + ) + + +class TelemetryConfig(proto.Message): + r"""Telemetry Configuration for the Dataproc Metastore service. + + Attributes: + log_format (google.cloud.metastore_v1alpha.types.TelemetryConfig.LogFormat): + The output format of the Dataproc Metastore + service's logs. + """ + class LogFormat(proto.Enum): + r""" + + Values: + LOG_FORMAT_UNSPECIFIED (0): + The LOG_FORMAT is not set. + LEGACY (1): + Logging output uses the legacy ``textPayload`` format. + JSON (2): + Logging output uses the ``jsonPayload`` format. + """ + LOG_FORMAT_UNSPECIFIED = 0 + LEGACY = 1 + JSON = 2 + + log_format: LogFormat = proto.Field( + proto.ENUM, + number=1, + enum=LogFormat, + ) + + +class MetadataManagementActivity(proto.Message): + r"""The metadata management activities of the metastore service. + + Attributes: + metadata_exports (MutableSequence[google.cloud.metastore_v1alpha.types.MetadataExport]): + Output only. The latest metadata exports of + the metastore service. + restores (MutableSequence[google.cloud.metastore_v1alpha.types.Restore]): + Output only. The latest restores of the + metastore service. + """ + + metadata_exports: MutableSequence['MetadataExport'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='MetadataExport', + ) + restores: MutableSequence['Restore'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Restore', + ) + + +class MetadataImport(proto.Message): + r"""A metastore resource that imports metadata. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + database_dump (google.cloud.metastore_v1alpha.types.MetadataImport.DatabaseDump): + Immutable. A database dump from a + pre-existing metastore's database. + + This field is a member of `oneof`_ ``metadata``. + name (str): + Immutable. The relative resource name of the metadata + import, of the form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports/{metadata_import_id}``. + description (str): + The description of the metadata import. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metadata + import was started. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metadata + import was last updated. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metadata + import finished. + state (google.cloud.metastore_v1alpha.types.MetadataImport.State): + Output only. The current state of the + metadata import. + """ + class State(proto.Enum): + r"""The current state of the metadata import. + + Values: + STATE_UNSPECIFIED (0): + The state of the metadata import is unknown. + RUNNING (1): + The metadata import is running. + SUCCEEDED (2): + The metadata import completed successfully. + UPDATING (3): + The metadata import is being updated. + FAILED (4): + The metadata import failed, and attempted + metadata changes were rolled back. + """ + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + UPDATING = 3 + FAILED = 4 + + class DatabaseDump(proto.Message): + r"""A specification of the location of and metadata about a + database dump from a relational database management system. + + Attributes: + database_type (google.cloud.metastore_v1alpha.types.MetadataImport.DatabaseDump.DatabaseType): + The type of the database. + gcs_uri (str): + A Cloud Storage object or folder URI that specifies the + source from which to import metadata. It must begin with + ``gs://``. + source_database (str): + The name of the source database. + type_ (google.cloud.metastore_v1alpha.types.DatabaseDumpSpec.Type): + Optional. The type of the database dump. If unspecified, + defaults to ``MYSQL``. + """ + class DatabaseType(proto.Enum): + r"""The type of the database. + + Values: + DATABASE_TYPE_UNSPECIFIED (0): + The type of the source database is unknown. + MYSQL (1): + The type of the source database is MySQL. + """ + DATABASE_TYPE_UNSPECIFIED = 0 + MYSQL = 1 + + database_type: 'MetadataImport.DatabaseDump.DatabaseType' = proto.Field( + proto.ENUM, + number=1, + enum='MetadataImport.DatabaseDump.DatabaseType', + ) + gcs_uri: str = proto.Field( + proto.STRING, + number=2, + ) + source_database: str = proto.Field( + proto.STRING, + number=3, + ) + type_: 'DatabaseDumpSpec.Type' = proto.Field( + proto.ENUM, + number=4, + enum='DatabaseDumpSpec.Type', + ) + + database_dump: DatabaseDump = proto.Field( + proto.MESSAGE, + number=6, + oneof='metadata', + message=DatabaseDump, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + state: State = proto.Field( + proto.ENUM, + number=5, + enum=State, + ) + + +class MetadataExport(proto.Message): + r"""The details of a metadata export operation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + destination_gcs_uri (str): + Output only. A Cloud Storage URI of a folder that metadata + are exported to, in the form of + ``gs:////``, + where ```` is automatically generated. + + This field is a member of `oneof`_ ``destination``. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the export + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the export ended. + state (google.cloud.metastore_v1alpha.types.MetadataExport.State): + Output only. The current state of the export. + database_dump_type (google.cloud.metastore_v1alpha.types.DatabaseDumpSpec.Type): + Output only. The type of the database dump. + """ + class State(proto.Enum): + r"""The current state of the metadata export. + + Values: + STATE_UNSPECIFIED (0): + The state of the metadata export is unknown. + RUNNING (1): + The metadata export is running. + SUCCEEDED (2): + The metadata export completed successfully. + FAILED (3): + The metadata export failed. + CANCELLED (4): + The metadata export is cancelled. + """ + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + FAILED = 3 + CANCELLED = 4 + + destination_gcs_uri: str = proto.Field( + proto.STRING, + number=4, + oneof='destination', + ) + start_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, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + database_dump_type: 'DatabaseDumpSpec.Type' = proto.Field( + proto.ENUM, + number=5, + enum='DatabaseDumpSpec.Type', + ) + + +class Backup(proto.Message): + r"""The details of a backup resource. + + Attributes: + name (str): + Immutable. The relative resource name of the backup, in the + following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the backup was + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the backup + finished creating. + state (google.cloud.metastore_v1alpha.types.Backup.State): + Output only. The current state of the backup. + service_revision (google.cloud.metastore_v1alpha.types.Service): + Output only. The revision of the service at + the time of backup. + description (str): + The description of the backup. + restoring_services (MutableSequence[str]): + Output only. Services that are restoring from + the backup. + """ + class State(proto.Enum): + r"""The current state of the backup. + + Values: + STATE_UNSPECIFIED (0): + The state of the backup is unknown. + CREATING (1): + The backup is being created. + DELETING (2): + The backup is being deleted. + ACTIVE (3): + The backup is active and ready to use. + FAILED (4): + The backup failed. + RESTORING (5): + The backup is being restored. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + DELETING = 2 + ACTIVE = 3 + FAILED = 4 + RESTORING = 5 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + service_revision: 'Service' = proto.Field( + proto.MESSAGE, + number=5, + message='Service', + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + restoring_services: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + +class Restore(proto.Message): + r"""The details of a metadata restore operation. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the restore + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the restore ended. + state (google.cloud.metastore_v1alpha.types.Restore.State): + Output only. The current state of the + restore. + backup (str): + Output only. The relative resource name of the metastore + service backup to restore from, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + type_ (google.cloud.metastore_v1alpha.types.Restore.RestoreType): + Output only. The type of restore. + details (str): + Output only. The restore details containing + the revision of the service to be restored to, + in format of JSON. + """ + class State(proto.Enum): + r"""The current state of the restore. + + Values: + STATE_UNSPECIFIED (0): + The state of the metadata restore is unknown. + RUNNING (1): + The metadata restore is running. + SUCCEEDED (2): + The metadata restore completed successfully. + FAILED (3): + The metadata restore failed. + CANCELLED (4): + The metadata restore is cancelled. + """ + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + FAILED = 3 + CANCELLED = 4 + + class RestoreType(proto.Enum): + r"""The type of restore. If unspecified, defaults to ``METADATA_ONLY``. + + Values: + RESTORE_TYPE_UNSPECIFIED (0): + The restore type is unknown. + FULL (1): + The service's metadata and configuration are + restored. + METADATA_ONLY (2): + Only the service's metadata is restored. + """ + RESTORE_TYPE_UNSPECIFIED = 0 + FULL = 1 + METADATA_ONLY = 2 + + start_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, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + backup: str = proto.Field( + proto.STRING, + number=4, + ) + type_: RestoreType = proto.Field( + proto.ENUM, + number=5, + enum=RestoreType, + ) + details: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ListServicesRequest(proto.Message): + r"""Request message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1alpha.DataprocMetastore.ListServices]. + + Attributes: + parent (str): + Required. The relative resource name of the location of + metastore services to list, in the following form: + + ``projects/{project_number}/locations/{location_id}``. + page_size (int): + Optional. The maximum number of services to + return. The response may contain less than the + maximum number. If unspecified, no more than 500 + services are returned. The maximum value is + 1000; values above 1000 are changed to 1000. + page_token (str): + Optional. A page token, received from a previous + [DataprocMetastore.ListServices][google.cloud.metastore.v1alpha.DataprocMetastore.ListServices] + call. Provide this token to retrieve the subsequent page. + + To retrieve the first page, supply an empty page token. + + When paginating, other parameters provided to + [DataprocMetastore.ListServices][google.cloud.metastore.v1alpha.DataprocMetastore.ListServices] + must match the call that provided the page token. + filter (str): + Optional. The filter to apply to list + results. + order_by (str): + Optional. Specify the ordering of results as described in + `Sorting + Order `__. + If not specified, the results will be sorted in the default + order. + """ + + 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 ListServicesResponse(proto.Message): + r"""Response message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1alpha.DataprocMetastore.ListServices]. + + Attributes: + services (MutableSequence[google.cloud.metastore_v1alpha.types.Service]): + The services in the specified location. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + services: MutableSequence['Service'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Service', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetServiceRequest(proto.Message): + r"""Request message for + [DataprocMetastore.GetService][google.cloud.metastore.v1alpha.DataprocMetastore.GetService]. + + Attributes: + name (str): + Required. The relative resource name of the metastore + service to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateServiceRequest(proto.Message): + r"""Request message for + [DataprocMetastore.CreateService][google.cloud.metastore.v1alpha.DataprocMetastore.CreateService]. + + Attributes: + parent (str): + Required. The relative resource name of the location in + which to create a metastore service, in the following form: + + ``projects/{project_number}/locations/{location_id}``. + service_id (str): + Required. The ID of the metastore service, + which is used as the final component of the + metastore service's name. + This value must be between 2 and 63 characters + long inclusive, begin with a letter, end with a + letter or number, and consist of alpha-numeric + ASCII characters or hyphens. + service (google.cloud.metastore_v1alpha.types.Service): + Required. The Metastore service to create. The ``name`` + field is ignored. The ID of the created metastore service + must be provided in the request's ``service_id`` field. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + service_id: str = proto.Field( + proto.STRING, + number=2, + ) + service: 'Service' = proto.Field( + proto.MESSAGE, + number=3, + message='Service', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateServiceRequest(proto.Message): + r"""Request message for + [DataprocMetastore.UpdateService][google.cloud.metastore.v1alpha.DataprocMetastore.UpdateService]. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask used to specify the fields to be + overwritten in the metastore service resource by the update. + Fields specified in the ``update_mask`` are relative to the + resource (not to the full request). A field is overwritten + if it is in the mask. + service (google.cloud.metastore_v1alpha.types.Service): + Required. The metastore service to update. The server only + merges fields in the service if they are specified in + ``update_mask``. + + The metastore service's ``name`` field is used to identify + the metastore service to be updated. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + service: 'Service' = proto.Field( + proto.MESSAGE, + number=2, + message='Service', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteServiceRequest(proto.Message): + r"""Request message for + [DataprocMetastore.DeleteService][google.cloud.metastore.v1alpha.DataprocMetastore.DeleteService]. + + Attributes: + name (str): + Required. The relative resource name of the metastore + service to delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListMetadataImportsRequest(proto.Message): + r"""Request message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1alpha.DataprocMetastore.ListMetadataImports]. + + Attributes: + parent (str): + Required. The relative resource name of the service whose + metadata imports to list, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports``. + page_size (int): + Optional. The maximum number of imports to + return. The response may contain less than the + maximum number. If unspecified, no more than 500 + imports are returned. The maximum value is 1000; + values above 1000 are changed to 1000. + page_token (str): + Optional. A page token, received from a previous + [DataprocMetastore.ListServices][google.cloud.metastore.v1alpha.DataprocMetastore.ListServices] + call. Provide this token to retrieve the subsequent page. + + To retrieve the first page, supply an empty page token. + + When paginating, other parameters provided to + [DataprocMetastore.ListServices][google.cloud.metastore.v1alpha.DataprocMetastore.ListServices] + must match the call that provided the page token. + filter (str): + Optional. The filter to apply to list + results. + order_by (str): + Optional. Specify the ordering of results as described in + `Sorting + Order `__. + If not specified, the results will be sorted in the default + order. + """ + + 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 ListMetadataImportsResponse(proto.Message): + r"""Response message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1alpha.DataprocMetastore.ListMetadataImports]. + + Attributes: + metadata_imports (MutableSequence[google.cloud.metastore_v1alpha.types.MetadataImport]): + The imports in the specified service. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + metadata_imports: MutableSequence['MetadataImport'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='MetadataImport', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetMetadataImportRequest(proto.Message): + r"""Request message for + [DataprocMetastore.GetMetadataImport][google.cloud.metastore.v1alpha.DataprocMetastore.GetMetadataImport]. + + Attributes: + name (str): + Required. The relative resource name of the metadata import + to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports/{import_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateMetadataImportRequest(proto.Message): + r"""Request message for + [DataprocMetastore.CreateMetadataImport][google.cloud.metastore.v1alpha.DataprocMetastore.CreateMetadataImport]. + + Attributes: + parent (str): + Required. The relative resource name of the service in which + to create a metastore import, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + metadata_import_id (str): + Required. The ID of the metadata import, + which is used as the final component of the + metadata import's name. + This value must be between 1 and 64 characters + long, begin with a letter, end with a letter or + number, and consist of alpha-numeric ASCII + characters or hyphens. + metadata_import (google.cloud.metastore_v1alpha.types.MetadataImport): + Required. The metadata import to create. The ``name`` field + is ignored. The ID of the created metadata import must be + provided in the request's ``metadata_import_id`` field. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + metadata_import_id: str = proto.Field( + proto.STRING, + number=2, + ) + metadata_import: 'MetadataImport' = proto.Field( + proto.MESSAGE, + number=3, + message='MetadataImport', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateMetadataImportRequest(proto.Message): + r"""Request message for + [DataprocMetastore.UpdateMetadataImport][google.cloud.metastore.v1alpha.DataprocMetastore.UpdateMetadataImport]. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask used to specify the fields to be + overwritten in the metadata import resource by the update. + Fields specified in the ``update_mask`` are relative to the + resource (not to the full request). A field is overwritten + if it is in the mask. + metadata_import (google.cloud.metastore_v1alpha.types.MetadataImport): + Required. The metadata import to update. The server only + merges fields in the import if they are specified in + ``update_mask``. + + The metadata import's ``name`` field is used to identify the + metastore import to be updated. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + metadata_import: 'MetadataImport' = proto.Field( + proto.MESSAGE, + number=2, + message='MetadataImport', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListBackupsRequest(proto.Message): + r"""Request message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1alpha.DataprocMetastore.ListBackups]. + + Attributes: + parent (str): + Required. The relative resource name of the service whose + backups to list, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups``. + page_size (int): + Optional. The maximum number of backups to + return. The response may contain less than the + maximum number. If unspecified, no more than 500 + backups are returned. The maximum value is 1000; + values above 1000 are changed to 1000. + page_token (str): + Optional. A page token, received from a previous + [DataprocMetastore.ListBackups][google.cloud.metastore.v1alpha.DataprocMetastore.ListBackups] + call. Provide this token to retrieve the subsequent page. + + To retrieve the first page, supply an empty page token. + + When paginating, other parameters provided to + [DataprocMetastore.ListBackups][google.cloud.metastore.v1alpha.DataprocMetastore.ListBackups] + must match the call that provided the page token. + filter (str): + Optional. The filter to apply to list + results. + order_by (str): + Optional. Specify the ordering of results as described in + `Sorting + Order `__. + If not specified, the results will be sorted in the default + order. + """ + + 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 ListBackupsResponse(proto.Message): + r"""Response message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1alpha.DataprocMetastore.ListBackups]. + + Attributes: + backups (MutableSequence[google.cloud.metastore_v1alpha.types.Backup]): + The backups of the specified service. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + backups: MutableSequence['Backup'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Backup', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetBackupRequest(proto.Message): + r"""Request message for + [DataprocMetastore.GetBackup][google.cloud.metastore.v1alpha.DataprocMetastore.GetBackup]. + + Attributes: + name (str): + Required. The relative resource name of the backup to + retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateBackupRequest(proto.Message): + r"""Request message for + [DataprocMetastore.CreateBackup][google.cloud.metastore.v1alpha.DataprocMetastore.CreateBackup]. + + Attributes: + parent (str): + Required. The relative resource name of the service in which + to create a backup of the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + backup_id (str): + Required. The ID of the backup, which is used + as the final component of the backup's name. + + This value must be between 1 and 64 characters + long, begin with a letter, end with a letter or + number, and consist of alpha-numeric ASCII + characters or hyphens. + backup (google.cloud.metastore_v1alpha.types.Backup): + Required. The backup to create. The ``name`` field is + ignored. The ID of the created backup must be provided in + the request's ``backup_id`` field. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + backup_id: str = proto.Field( + proto.STRING, + number=2, + ) + backup: 'Backup' = proto.Field( + proto.MESSAGE, + number=3, + message='Backup', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class DeleteBackupRequest(proto.Message): + r"""Request message for + [DataprocMetastore.DeleteBackup][google.cloud.metastore.v1alpha.DataprocMetastore.DeleteBackup]. + + Attributes: + name (str): + Required. The relative resource name of the backup to + delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ExportMetadataRequest(proto.Message): + r"""Request message for + [DataprocMetastore.ExportMetadata][google.cloud.metastore.v1alpha.DataprocMetastore.ExportMetadata]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + destination_gcs_folder (str): + A Cloud Storage URI of a folder, in the format + ``gs:///``. A sub-folder + ```` containing exported files will be + created below it. + + This field is a member of `oneof`_ ``destination``. + service (str): + Required. The relative resource name of the metastore + service to run export, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}``. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__. + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + database_dump_type (google.cloud.metastore_v1alpha.types.DatabaseDumpSpec.Type): + Optional. The type of the database dump. If unspecified, + defaults to ``MYSQL``. + """ + + destination_gcs_folder: str = proto.Field( + proto.STRING, + number=2, + oneof='destination', + ) + service: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + database_dump_type: 'DatabaseDumpSpec.Type' = proto.Field( + proto.ENUM, + number=4, + enum='DatabaseDumpSpec.Type', + ) + + +class RestoreServiceRequest(proto.Message): + r"""Request message for [DataprocMetastore.Restore][]. + + Attributes: + service (str): + Required. The relative resource name of the metastore + service to run restore, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}``. + backup (str): + Required. The relative resource name of the metastore + service backup to restore from, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + restore_type (google.cloud.metastore_v1alpha.types.Restore.RestoreType): + Optional. The type of restore. If unspecified, defaults to + ``METADATA_ONLY``. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__. + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + service: str = proto.Field( + proto.STRING, + number=1, + ) + backup: str = proto.Field( + proto.STRING, + number=2, + ) + restore_type: 'Restore.RestoreType' = proto.Field( + proto.ENUM, + number=3, + enum='Restore.RestoreType', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of a 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 caller has requested + cancellation of the operation. Operations that have + successfully been cancelled 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 LocationMetadata(proto.Message): + r"""Metadata about the service in a location. + + Attributes: + supported_hive_metastore_versions (MutableSequence[google.cloud.metastore_v1alpha.types.LocationMetadata.HiveMetastoreVersion]): + The versions of Hive Metastore that can be used when + creating a new metastore service in this location. The + server guarantees that exactly one ``HiveMetastoreVersion`` + in the list will set ``is_default``. + """ + + class HiveMetastoreVersion(proto.Message): + r"""A specification of a supported version of the Hive Metastore + software. + + Attributes: + version (str): + The semantic version of the Hive Metastore + software. + is_default (bool): + Whether ``version`` will be chosen by the server if a + metastore service is created with a ``HiveMetastoreConfig`` + that omits the ``version``. + """ + + version: str = proto.Field( + proto.STRING, + number=1, + ) + is_default: bool = proto.Field( + proto.BOOL, + number=2, + ) + + supported_hive_metastore_versions: MutableSequence[HiveMetastoreVersion] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=HiveMetastoreVersion, + ) + + +class DatabaseDumpSpec(proto.Message): + r"""The specification of database dump to import from or export + to. + + """ + class Type(proto.Enum): + r"""The type of the database dump. + + Values: + TYPE_UNSPECIFIED (0): + The type of the database dump is unknown. + MYSQL (1): + Database dump is a MySQL dump file. + AVRO (2): + Database dump contains Avro files. + """ + TYPE_UNSPECIFIED = 0 + MYSQL = 1 + AVRO = 2 + + +class RemoveIamPolicyRequest(proto.Message): + r"""Request message for + [DataprocMetastore.RemoveIamPolicy][google.cloud.metastore.v1alpha.DataprocMetastore.RemoveIamPolicy]. + + Attributes: + resource (str): + Required. The relative resource name of the dataplane + resource to remove IAM policy, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}/databases/{database_id}`` + or + ``projects/{project_id}/locations/{location_id}/services/{service_id}/databases/{database_id}/tables/{table_id}``. + asynchronous (bool): + Optional. Removes IAM policy attached to + database or table asynchronously when it is set. + The default is false. + """ + + resource: str = proto.Field( + proto.STRING, + number=1, + ) + asynchronous: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class RemoveIamPolicyResponse(proto.Message): + r"""Response message for + [DataprocMetastore.RemoveIamPolicy][google.cloud.metastore.v1alpha.DataprocMetastore.RemoveIamPolicy]. + + Attributes: + success (bool): + True if the policy is successfully removed. + """ + + success: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +class QueryMetadataRequest(proto.Message): + r"""Request message for + [DataprocMetastore.QueryMetadata][google.cloud.metastore.v1alpha.DataprocMetastore.QueryMetadata]. + + Attributes: + service (str): + Required. The relative resource name of the metastore + service to query metadata, in the following format: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}``. + query (str): + Required. A read-only SQL query to execute + against the metadata database. The query cannot + change or mutate the data. + """ + + service: str = proto.Field( + proto.STRING, + number=1, + ) + query: str = proto.Field( + proto.STRING, + number=2, + ) + + +class QueryMetadataResponse(proto.Message): + r"""Response message for + [DataprocMetastore.QueryMetadata][google.cloud.metastore.v1alpha.DataprocMetastore.QueryMetadata]. + + Attributes: + result_manifest_uri (str): + The manifest URI is link to a JSON instance + in Cloud Storage. This instance manifests + immediately along with QueryMetadataResponse. + The content of the URI is not retriable until + the long-running operation query against the + metadata finishes. + """ + + result_manifest_uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +class MoveTableToDatabaseRequest(proto.Message): + r"""Request message for + [DataprocMetastore.MoveTableToDatabase][google.cloud.metastore.v1alpha.DataprocMetastore.MoveTableToDatabase]. + + Attributes: + service (str): + Required. The relative resource name of the metastore + service to mutate metadata, in the following format: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}``. + table_name (str): + Required. The name of the table to be moved. + db_name (str): + Required. The name of the database where the + table resides. + destination_db_name (str): + Required. The name of the database where the + table should be moved. + """ + + service: str = proto.Field( + proto.STRING, + number=1, + ) + table_name: str = proto.Field( + proto.STRING, + number=2, + ) + db_name: str = proto.Field( + proto.STRING, + number=3, + ) + destination_db_name: str = proto.Field( + proto.STRING, + number=4, + ) + + +class MoveTableToDatabaseResponse(proto.Message): + r"""Response message for + [DataprocMetastore.MoveTableToDatabase][google.cloud.metastore.v1alpha.DataprocMetastore.MoveTableToDatabase]. + + """ + + +class AlterMetadataResourceLocationRequest(proto.Message): + r"""Request message for + [DataprocMetastore.AlterMetadataResourceLocation][google.cloud.metastore.v1alpha.DataprocMetastore.AlterMetadataResourceLocation]. + + Attributes: + service (str): + Required. The relative resource name of the metastore + service to mutate metadata, in the following format: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}``. + resource_name (str): + Required. The relative metadata resource name in the + following format. + + ``databases/{database_id}`` or + ``databases/{database_id}/tables/{table_id}`` or + ``databases/{database_id}/tables/{table_id}/partitions/{partition_id}`` + location_uri (str): + Required. The new location URI for the + metadata resource. + """ + + service: str = proto.Field( + proto.STRING, + number=1, + ) + resource_name: str = proto.Field( + proto.STRING, + number=2, + ) + location_uri: str = proto.Field( + proto.STRING, + number=3, + ) + + +class AlterMetadataResourceLocationResponse(proto.Message): + r"""Response message for + [DataprocMetastore.AlterMetadataResourceLocation][google.cloud.metastore.v1alpha.DataprocMetastore.AlterMetadataResourceLocation]. + + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/types/metastore_federation.py b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/types/metastore_federation.py new file mode 100644 index 0000000..d3abb01 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/metastore_v1alpha/types/metastore_federation.py @@ -0,0 +1,466 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.metastore.v1alpha', + manifest={ + 'Federation', + 'BackendMetastore', + 'ListFederationsRequest', + 'ListFederationsResponse', + 'GetFederationRequest', + 'CreateFederationRequest', + 'UpdateFederationRequest', + 'DeleteFederationRequest', + }, +) + + +class Federation(proto.Message): + r"""Represents a federation of multiple backend metastores. + + Attributes: + name (str): + Immutable. The relative resource name of the federation, of + the form: + projects/{project_number}/locations/{location_id}/federations/{federation_id}`. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metastore + federation was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metastore + federation was last updated. + labels (MutableMapping[str, str]): + User-defined labels for the metastore + federation. + version (str): + Immutable. The Apache Hive metastore version + of the federation. All backend metastore + versions must be compatible with the federation + version. + backend_metastores (MutableMapping[int, google.cloud.metastore_v1alpha.types.BackendMetastore]): + A map from ``BackendMetastore`` rank to + ``BackendMetastore``\ s from which the federation service + serves metadata at query time. The map key represents the + order in which ``BackendMetastore``\ s should be evaluated + to resolve database names at query time and should be + greater than or equal to zero. A ``BackendMetastore`` with a + lower number will be evaluated before a ``BackendMetastore`` + with a higher number. + endpoint_uri (str): + Output only. The federation endpoint. + state (google.cloud.metastore_v1alpha.types.Federation.State): + Output only. The current state of the + federation. + state_message (str): + Output only. Additional information about the + current state of the metastore federation, if + available. + uid (str): + Output only. The globally unique resource + identifier of the metastore federation. + """ + class State(proto.Enum): + r"""The current state of the federation. + + Values: + STATE_UNSPECIFIED (0): + The state of the metastore federation is + unknown. + CREATING (1): + The metastore federation is in the process of + being created. + ACTIVE (2): + The metastore federation is running and ready + to serve queries. + UPDATING (3): + The metastore federation is being updated. It + remains usable but cannot accept additional + update requests or be deleted at this time. + DELETING (4): + The metastore federation is undergoing + deletion. It cannot be used. + ERROR (5): + The metastore federation has encountered an + error and cannot be used. The metastore + federation should be deleted. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + UPDATING = 3 + DELETING = 4 + ERROR = 5 + + 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, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + version: str = proto.Field( + proto.STRING, + number=5, + ) + backend_metastores: MutableMapping[int, 'BackendMetastore'] = proto.MapField( + proto.INT32, + proto.MESSAGE, + number=6, + message='BackendMetastore', + ) + endpoint_uri: str = proto.Field( + proto.STRING, + number=7, + ) + state: State = proto.Field( + proto.ENUM, + number=8, + enum=State, + ) + state_message: str = proto.Field( + proto.STRING, + number=9, + ) + uid: str = proto.Field( + proto.STRING, + number=10, + ) + + +class BackendMetastore(proto.Message): + r"""Represents a backend metastore for the federation. + + Attributes: + name (str): + The relative resource name of the metastore that is being + federated. The formats of the relative resource names for + the currently supported metastores are listed below: + + - Dataplex + + - ``projects/{project_id}/locations/{location}/lakes/{lake_id}`` + + - BigQuery + + - ``projects/{project_id}`` + + - Dataproc Metastore + + - ``projects/{project_id}/locations/{location}/services/{service_id}`` + metastore_type (google.cloud.metastore_v1alpha.types.BackendMetastore.MetastoreType): + The type of the backend metastore. + """ + class MetastoreType(proto.Enum): + r"""The type of the backend metastore. + + Values: + METASTORE_TYPE_UNSPECIFIED (0): + The metastore type is not set. + BIGQUERY (2): + The backend metastore is BigQuery. + DATAPROC_METASTORE (3): + The backend metastore is Dataproc Metastore. + """ + METASTORE_TYPE_UNSPECIFIED = 0 + BIGQUERY = 2 + DATAPROC_METASTORE = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + metastore_type: MetastoreType = proto.Field( + proto.ENUM, + number=2, + enum=MetastoreType, + ) + + +class ListFederationsRequest(proto.Message): + r"""Request message for ListFederations. + + Attributes: + parent (str): + Required. The relative resource name of the location of + metastore federations to list, in the following form: + ``projects/{project_number}/locations/{location_id}``. + page_size (int): + Optional. The maximum number of federations + to return. The response may contain less than + the maximum number. If unspecified, no more than + 500 services are returned. The maximum value is + 1000; values above 1000 are changed to 1000. + page_token (str): + Optional. A page token, received from a + previous ListFederationServices call. Provide + this token to retrieve the subsequent page. + To retrieve the first page, supply an empty page + token. + When paginating, other parameters provided to + ListFederationServices must match the call that + provided the page token. + filter (str): + Optional. The filter to apply to list + results. + order_by (str): + Optional. Specify the ordering of results as described in + `Sorting + Order `__. + If not specified, the results will be sorted in the default + order. + """ + + 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 ListFederationsResponse(proto.Message): + r"""Response message for ListFederations + + Attributes: + federations (MutableSequence[google.cloud.metastore_v1alpha.types.Federation]): + The services in the specified location. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + federations: MutableSequence['Federation'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Federation', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetFederationRequest(proto.Message): + r"""Request message for GetFederation. + + Attributes: + name (str): + Required. The relative resource name of the metastore + federation to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateFederationRequest(proto.Message): + r"""Request message for CreateFederation. + + Attributes: + parent (str): + Required. The relative resource name of the location in + which to create a federation service, in the following form: + + ``projects/{project_number}/locations/{location_id}``. + federation_id (str): + Required. The ID of the metastore federation, + which is used as the final component of the + metastore federation's name. + This value must be between 2 and 63 characters + long inclusive, begin with a letter, end with a + letter or number, and consist of alpha-numeric + ASCII characters or hyphens. + federation (google.cloud.metastore_v1alpha.types.Federation): + Required. The Metastore Federation to create. The ``name`` + field is ignored. The ID of the created metastore federation + must be provided in the request's ``federation_id`` field. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + federation_id: str = proto.Field( + proto.STRING, + number=2, + ) + federation: 'Federation' = proto.Field( + proto.MESSAGE, + number=3, + message='Federation', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateFederationRequest(proto.Message): + r"""Request message for UpdateFederation. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask used to specify the fields to be + overwritten in the metastore federation resource by the + update. Fields specified in the ``update_mask`` are relative + to the resource (not to the full request). A field is + overwritten if it is in the mask. + federation (google.cloud.metastore_v1alpha.types.Federation): + Required. The metastore federation to update. The server + only merges fields in the service if they are specified in + ``update_mask``. + + The metastore federation's ``name`` field is used to + identify the metastore service to be updated. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + federation: 'Federation' = proto.Field( + proto.MESSAGE, + number=2, + message='Federation', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteFederationRequest(proto.Message): + r"""Request message for DeleteFederation. + + Attributes: + name (str): + Required. The relative resource name of the metastore + federation to delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/mypy.ini b/owl-bot-staging/v1alpha/mypy.ini new file mode 100644 index 0000000..574c5ae --- /dev/null +++ b/owl-bot-staging/v1alpha/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1alpha/noxfile.py b/owl-bot-staging/v1alpha/noxfile.py new file mode 100644 index 0000000..1b4a747 --- /dev/null +++ b/owl-bot-staging/v1alpha/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "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/metastore_v1alpha/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-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/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_alter_metadata_resource_location_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_alter_metadata_resource_location_async.py new file mode 100644 index 0000000..dc31884 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_alter_metadata_resource_location_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AlterMetadataResourceLocation +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_AlterMetadataResourceLocation_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 metastore_v1alpha + + +async def sample_alter_metadata_resource_location(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.AlterMetadataResourceLocationRequest( + service="service_value", + resource_name="resource_name_value", + location_uri="location_uri_value", + ) + + # Make the request + operation = client.alter_metadata_resource_location(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_AlterMetadataResourceLocation_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_alter_metadata_resource_location_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_alter_metadata_resource_location_sync.py new file mode 100644 index 0000000..9660fd8 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_alter_metadata_resource_location_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AlterMetadataResourceLocation +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_AlterMetadataResourceLocation_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 metastore_v1alpha + + +def sample_alter_metadata_resource_location(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.AlterMetadataResourceLocationRequest( + service="service_value", + resource_name="resource_name_value", + location_uri="location_uri_value", + ) + + # Make the request + operation = client.alter_metadata_resource_location(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_AlterMetadataResourceLocation_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_create_backup_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_create_backup_async.py new file mode 100644 index 0000000..5ffea86 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_create_backup_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateBackup +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_CreateBackup_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 metastore_v1alpha + + +async def sample_create_backup(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + ) + + # Make the request + operation = client.create_backup(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_CreateBackup_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_create_backup_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_create_backup_sync.py new file mode 100644 index 0000000..e0d1927 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_create_backup_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateBackup +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_CreateBackup_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 metastore_v1alpha + + +def sample_create_backup(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + ) + + # Make the request + operation = client.create_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_CreateBackup_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_create_metadata_import_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_create_metadata_import_async.py new file mode 100644 index 0000000..a08e079 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_create_metadata_import_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMetadataImport +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_CreateMetadataImport_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 metastore_v1alpha + + +async def sample_create_metadata_import(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.CreateMetadataImportRequest( + parent="parent_value", + metadata_import_id="metadata_import_id_value", + ) + + # Make the request + operation = client.create_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_CreateMetadataImport_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_create_metadata_import_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_create_metadata_import_sync.py new file mode 100644 index 0000000..617e51b --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_create_metadata_import_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMetadataImport +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_CreateMetadataImport_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 metastore_v1alpha + + +def sample_create_metadata_import(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.CreateMetadataImportRequest( + parent="parent_value", + metadata_import_id="metadata_import_id_value", + ) + + # Make the request + operation = client.create_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_CreateMetadataImport_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_create_service_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_create_service_async.py new file mode 100644 index 0000000..fa6cebb --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_create_service_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateService +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_CreateService_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 metastore_v1alpha + + +async def sample_create_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.CreateServiceRequest( + parent="parent_value", + service_id="service_id_value", + ) + + # Make the request + operation = client.create_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_CreateService_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_create_service_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_create_service_sync.py new file mode 100644 index 0000000..781c5da --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_create_service_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateService +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_CreateService_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 metastore_v1alpha + + +def sample_create_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.CreateServiceRequest( + parent="parent_value", + service_id="service_id_value", + ) + + # Make the request + operation = client.create_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_CreateService_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_delete_backup_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_delete_backup_async.py new file mode 100644 index 0000000..885d7a0 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_delete_backup_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteBackup +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_DeleteBackup_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 metastore_v1alpha + + +async def sample_delete_backup(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_DeleteBackup_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_delete_backup_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_delete_backup_sync.py new file mode 100644 index 0000000..0a3890b --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_delete_backup_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteBackup +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_DeleteBackup_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 metastore_v1alpha + + +def sample_delete_backup(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_DeleteBackup_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_delete_service_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_delete_service_async.py new file mode 100644 index 0000000..07c45a9 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_delete_service_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteService +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_DeleteService_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 metastore_v1alpha + + +async def sample_delete_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.DeleteServiceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_DeleteService_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_delete_service_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_delete_service_sync.py new file mode 100644 index 0000000..2cb7e29 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_delete_service_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteService +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_DeleteService_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 metastore_v1alpha + + +def sample_delete_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.DeleteServiceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_DeleteService_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_export_metadata_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_export_metadata_async.py new file mode 100644 index 0000000..327a8f6 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_export_metadata_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExportMetadata +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_ExportMetadata_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 metastore_v1alpha + + +async def sample_export_metadata(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ExportMetadataRequest( + destination_gcs_folder="destination_gcs_folder_value", + service="service_value", + ) + + # Make the request + operation = client.export_metadata(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_ExportMetadata_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_export_metadata_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_export_metadata_sync.py new file mode 100644 index 0000000..82b1b35 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_export_metadata_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExportMetadata +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_ExportMetadata_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 metastore_v1alpha + + +def sample_export_metadata(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ExportMetadataRequest( + destination_gcs_folder="destination_gcs_folder_value", + service="service_value", + ) + + # Make the request + operation = client.export_metadata(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_ExportMetadata_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_create_federation_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_create_federation_async.py new file mode 100644 index 0000000..71b27b8 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_create_federation_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateFederation +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastoreFederation_CreateFederation_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 metastore_v1alpha + + +async def sample_create_federation(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.CreateFederationRequest( + parent="parent_value", + federation_id="federation_id_value", + ) + + # Make the request + operation = client.create_federation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastoreFederation_CreateFederation_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_create_federation_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_create_federation_sync.py new file mode 100644 index 0000000..7525aa0 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_create_federation_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateFederation +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastoreFederation_CreateFederation_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 metastore_v1alpha + + +def sample_create_federation(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1alpha.CreateFederationRequest( + parent="parent_value", + federation_id="federation_id_value", + ) + + # Make the request + operation = client.create_federation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastoreFederation_CreateFederation_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_delete_federation_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_delete_federation_async.py new file mode 100644 index 0000000..1b3ad6a --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_delete_federation_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteFederation +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastoreFederation_DeleteFederation_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 metastore_v1alpha + + +async def sample_delete_federation(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.DeleteFederationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_federation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastoreFederation_DeleteFederation_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_delete_federation_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_delete_federation_sync.py new file mode 100644 index 0000000..a43c7d5 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_delete_federation_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteFederation +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastoreFederation_DeleteFederation_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 metastore_v1alpha + + +def sample_delete_federation(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1alpha.DeleteFederationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_federation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastoreFederation_DeleteFederation_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_get_federation_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_get_federation_async.py new file mode 100644 index 0000000..85fcb91 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_get_federation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFederation +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastoreFederation_GetFederation_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 metastore_v1alpha + + +async def sample_get_federation(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.GetFederationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_federation(request=request) + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastoreFederation_GetFederation_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_get_federation_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_get_federation_sync.py new file mode 100644 index 0000000..3e84d21 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_get_federation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFederation +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastoreFederation_GetFederation_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 metastore_v1alpha + + +def sample_get_federation(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1alpha.GetFederationRequest( + name="name_value", + ) + + # Make the request + response = client.get_federation(request=request) + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastoreFederation_GetFederation_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_list_federations_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_list_federations_async.py new file mode 100644 index 0000000..12b8c97 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_list_federations_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListFederations +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastoreFederation_ListFederations_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 metastore_v1alpha + + +async def sample_list_federations(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ListFederationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_federations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastoreFederation_ListFederations_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_list_federations_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_list_federations_sync.py new file mode 100644 index 0000000..e7f46a1 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_list_federations_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListFederations +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastoreFederation_ListFederations_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 metastore_v1alpha + + +def sample_list_federations(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ListFederationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_federations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastoreFederation_ListFederations_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_update_federation_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_update_federation_async.py new file mode 100644 index 0000000..e5ee982 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_update_federation_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateFederation +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastoreFederation_UpdateFederation_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 metastore_v1alpha + + +async def sample_update_federation(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.UpdateFederationRequest( + ) + + # Make the request + operation = client.update_federation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastoreFederation_UpdateFederation_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_update_federation_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_update_federation_sync.py new file mode 100644 index 0000000..043b725 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_federation_update_federation_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateFederation +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastoreFederation_UpdateFederation_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 metastore_v1alpha + + +def sample_update_federation(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1alpha.UpdateFederationRequest( + ) + + # Make the request + operation = client.update_federation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastoreFederation_UpdateFederation_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_get_backup_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_get_backup_async.py new file mode 100644 index 0000000..60b0f22 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_get_backup_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBackup +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_GetBackup_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 metastore_v1alpha + + +async def sample_get_backup(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup(request=request) + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_GetBackup_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_get_backup_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_get_backup_sync.py new file mode 100644 index 0000000..0fc4889 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_get_backup_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBackup +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_GetBackup_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 metastore_v1alpha + + +def sample_get_backup(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup(request=request) + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_GetBackup_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_get_metadata_import_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_get_metadata_import_async.py new file mode 100644 index 0000000..7c56851 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_get_metadata_import_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMetadataImport +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_GetMetadataImport_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 metastore_v1alpha + + +async def sample_get_metadata_import(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.GetMetadataImportRequest( + name="name_value", + ) + + # Make the request + response = await client.get_metadata_import(request=request) + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_GetMetadataImport_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_get_metadata_import_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_get_metadata_import_sync.py new file mode 100644 index 0000000..fc35d7b --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_get_metadata_import_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMetadataImport +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_GetMetadataImport_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 metastore_v1alpha + + +def sample_get_metadata_import(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.GetMetadataImportRequest( + name="name_value", + ) + + # Make the request + response = client.get_metadata_import(request=request) + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_GetMetadataImport_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_get_service_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_get_service_async.py new file mode 100644 index 0000000..60b69fb --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_get_service_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetService +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_GetService_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 metastore_v1alpha + + +async def sample_get_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.GetServiceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_service(request=request) + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_GetService_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_get_service_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_get_service_sync.py new file mode 100644 index 0000000..230e93f --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_get_service_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetService +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_GetService_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 metastore_v1alpha + + +def sample_get_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.GetServiceRequest( + name="name_value", + ) + + # Make the request + response = client.get_service(request=request) + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_GetService_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_list_backups_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_list_backups_async.py new file mode 100644 index 0000000..7b88c87 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_list_backups_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBackups +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_ListBackups_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 metastore_v1alpha + + +async def sample_list_backups(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_ListBackups_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_list_backups_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_list_backups_sync.py new file mode 100644 index 0000000..cd6f465 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_list_backups_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBackups +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_ListBackups_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 metastore_v1alpha + + +def sample_list_backups(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_ListBackups_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_list_metadata_imports_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_list_metadata_imports_async.py new file mode 100644 index 0000000..c8f4935 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_list_metadata_imports_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMetadataImports +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_ListMetadataImports_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 metastore_v1alpha + + +async def sample_list_metadata_imports(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ListMetadataImportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_metadata_imports(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_ListMetadataImports_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_list_metadata_imports_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_list_metadata_imports_sync.py new file mode 100644 index 0000000..ceb4ff2 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_list_metadata_imports_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMetadataImports +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_ListMetadataImports_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 metastore_v1alpha + + +def sample_list_metadata_imports(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ListMetadataImportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_metadata_imports(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_ListMetadataImports_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_list_services_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_list_services_async.py new file mode 100644 index 0000000..5358cff --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_list_services_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServices +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_ListServices_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 metastore_v1alpha + + +async def sample_list_services(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ListServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_ListServices_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_list_services_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_list_services_sync.py new file mode 100644 index 0000000..33f4f1d --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_list_services_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServices +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_ListServices_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 metastore_v1alpha + + +def sample_list_services(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.ListServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_ListServices_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_move_table_to_database_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_move_table_to_database_async.py new file mode 100644 index 0000000..35657bf --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_move_table_to_database_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MoveTableToDatabase +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_MoveTableToDatabase_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 metastore_v1alpha + + +async def sample_move_table_to_database(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.MoveTableToDatabaseRequest( + service="service_value", + table_name="table_name_value", + db_name="db_name_value", + destination_db_name="destination_db_name_value", + ) + + # Make the request + operation = client.move_table_to_database(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_MoveTableToDatabase_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_move_table_to_database_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_move_table_to_database_sync.py new file mode 100644 index 0000000..28b02cd --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_move_table_to_database_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MoveTableToDatabase +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_MoveTableToDatabase_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 metastore_v1alpha + + +def sample_move_table_to_database(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.MoveTableToDatabaseRequest( + service="service_value", + table_name="table_name_value", + db_name="db_name_value", + destination_db_name="destination_db_name_value", + ) + + # Make the request + operation = client.move_table_to_database(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_MoveTableToDatabase_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_query_metadata_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_query_metadata_async.py new file mode 100644 index 0000000..94f6645 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_query_metadata_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for QueryMetadata +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_QueryMetadata_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 metastore_v1alpha + + +async def sample_query_metadata(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.QueryMetadataRequest( + service="service_value", + query="query_value", + ) + + # Make the request + operation = client.query_metadata(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_QueryMetadata_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_query_metadata_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_query_metadata_sync.py new file mode 100644 index 0000000..9bcbe6a --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_query_metadata_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for QueryMetadata +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_QueryMetadata_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 metastore_v1alpha + + +def sample_query_metadata(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.QueryMetadataRequest( + service="service_value", + query="query_value", + ) + + # Make the request + operation = client.query_metadata(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_QueryMetadata_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_remove_iam_policy_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_remove_iam_policy_async.py new file mode 100644 index 0000000..68c4683 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_remove_iam_policy_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveIamPolicy +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_RemoveIamPolicy_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 metastore_v1alpha + + +async def sample_remove_iam_policy(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.RemoveIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.remove_iam_policy(request=request) + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_RemoveIamPolicy_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_remove_iam_policy_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_remove_iam_policy_sync.py new file mode 100644 index 0000000..507f51b --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_remove_iam_policy_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveIamPolicy +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_RemoveIamPolicy_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 metastore_v1alpha + + +def sample_remove_iam_policy(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.RemoveIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.remove_iam_policy(request=request) + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_RemoveIamPolicy_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_restore_service_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_restore_service_async.py new file mode 100644 index 0000000..ab29aa1 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_restore_service_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreService +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_RestoreService_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 metastore_v1alpha + + +async def sample_restore_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.RestoreServiceRequest( + service="service_value", + backup="backup_value", + ) + + # Make the request + operation = client.restore_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_RestoreService_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_restore_service_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_restore_service_sync.py new file mode 100644 index 0000000..bab5c0c --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_restore_service_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreService +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_RestoreService_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 metastore_v1alpha + + +def sample_restore_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.RestoreServiceRequest( + service="service_value", + backup="backup_value", + ) + + # Make the request + operation = client.restore_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_RestoreService_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_update_metadata_import_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_update_metadata_import_async.py new file mode 100644 index 0000000..6aeece1 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_update_metadata_import_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMetadataImport +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_UpdateMetadataImport_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 metastore_v1alpha + + +async def sample_update_metadata_import(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.UpdateMetadataImportRequest( + ) + + # Make the request + operation = client.update_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_UpdateMetadataImport_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_update_metadata_import_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_update_metadata_import_sync.py new file mode 100644 index 0000000..88eb58f --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_update_metadata_import_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMetadataImport +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_UpdateMetadataImport_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 metastore_v1alpha + + +def sample_update_metadata_import(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.UpdateMetadataImportRequest( + ) + + # Make the request + operation = client.update_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_UpdateMetadataImport_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_update_service_async.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_update_service_async.py new file mode 100644 index 0000000..d715973 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_update_service_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateService +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_UpdateService_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 metastore_v1alpha + + +async def sample_update_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1alpha.UpdateServiceRequest( + ) + + # Make the request + operation = client.update_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_UpdateService_async] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_update_service_sync.py b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_update_service_sync.py new file mode 100644 index 0000000..70a37c2 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/metastore_v1alpha_generated_dataproc_metastore_update_service_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateService +# 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-dataproc-metastore + + +# [START metastore_v1alpha_generated_DataprocMetastore_UpdateService_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 metastore_v1alpha + + +def sample_update_service(): + # Create a client + client = metastore_v1alpha.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1alpha.UpdateServiceRequest( + ) + + # Make the request + operation = client.update_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1alpha_generated_DataprocMetastore_UpdateService_sync] diff --git a/owl-bot-staging/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1alpha.json b/owl-bot-staging/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1alpha.json new file mode 100644 index 0000000..96abac7 --- /dev/null +++ b/owl-bot-staging/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1alpha.json @@ -0,0 +1,3935 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.metastore.v1alpha", + "version": "v1alpha" + } + ], + "language": "PYTHON", + "name": "google-cloud-dataproc-metastore", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationAsyncClient", + "shortName": "DataprocMetastoreFederationAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationAsyncClient.create_federation", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation.CreateFederation", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "CreateFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.CreateFederationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "federation", + "type": "google.cloud.metastore_v1alpha.types.Federation" + }, + { + "name": "federation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_federation" + }, + "description": "Sample for CreateFederation", + "file": "metastore_v1alpha_generated_dataproc_metastore_federation_create_federation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastoreFederation_CreateFederation_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_federation_create_federation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationClient", + "shortName": "DataprocMetastoreFederationClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationClient.create_federation", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation.CreateFederation", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "CreateFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.CreateFederationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "federation", + "type": "google.cloud.metastore_v1alpha.types.Federation" + }, + { + "name": "federation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_federation" + }, + "description": "Sample for CreateFederation", + "file": "metastore_v1alpha_generated_dataproc_metastore_federation_create_federation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastoreFederation_CreateFederation_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_federation_create_federation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationAsyncClient", + "shortName": "DataprocMetastoreFederationAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationAsyncClient.delete_federation", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation.DeleteFederation", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "DeleteFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.DeleteFederationRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "delete_federation" + }, + "description": "Sample for DeleteFederation", + "file": "metastore_v1alpha_generated_dataproc_metastore_federation_delete_federation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastoreFederation_DeleteFederation_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_federation_delete_federation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationClient", + "shortName": "DataprocMetastoreFederationClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationClient.delete_federation", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation.DeleteFederation", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "DeleteFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.DeleteFederationRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "delete_federation" + }, + "description": "Sample for DeleteFederation", + "file": "metastore_v1alpha_generated_dataproc_metastore_federation_delete_federation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastoreFederation_DeleteFederation_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_federation_delete_federation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationAsyncClient", + "shortName": "DataprocMetastoreFederationAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationAsyncClient.get_federation", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation.GetFederation", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "GetFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.GetFederationRequest" + }, + { + "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.metastore_v1alpha.types.Federation", + "shortName": "get_federation" + }, + "description": "Sample for GetFederation", + "file": "metastore_v1alpha_generated_dataproc_metastore_federation_get_federation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastoreFederation_GetFederation_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": "metastore_v1alpha_generated_dataproc_metastore_federation_get_federation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationClient", + "shortName": "DataprocMetastoreFederationClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationClient.get_federation", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation.GetFederation", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "GetFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.GetFederationRequest" + }, + { + "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.metastore_v1alpha.types.Federation", + "shortName": "get_federation" + }, + "description": "Sample for GetFederation", + "file": "metastore_v1alpha_generated_dataproc_metastore_federation_get_federation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastoreFederation_GetFederation_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": "metastore_v1alpha_generated_dataproc_metastore_federation_get_federation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationAsyncClient", + "shortName": "DataprocMetastoreFederationAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationAsyncClient.list_federations", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation.ListFederations", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "ListFederations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.ListFederationsRequest" + }, + { + "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.metastore_v1alpha.services.dataproc_metastore_federation.pagers.ListFederationsAsyncPager", + "shortName": "list_federations" + }, + "description": "Sample for ListFederations", + "file": "metastore_v1alpha_generated_dataproc_metastore_federation_list_federations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastoreFederation_ListFederations_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": "metastore_v1alpha_generated_dataproc_metastore_federation_list_federations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationClient", + "shortName": "DataprocMetastoreFederationClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationClient.list_federations", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation.ListFederations", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "ListFederations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.ListFederationsRequest" + }, + { + "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.metastore_v1alpha.services.dataproc_metastore_federation.pagers.ListFederationsPager", + "shortName": "list_federations" + }, + "description": "Sample for ListFederations", + "file": "metastore_v1alpha_generated_dataproc_metastore_federation_list_federations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastoreFederation_ListFederations_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": "metastore_v1alpha_generated_dataproc_metastore_federation_list_federations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationAsyncClient", + "shortName": "DataprocMetastoreFederationAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationAsyncClient.update_federation", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation.UpdateFederation", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "UpdateFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.UpdateFederationRequest" + }, + { + "name": "federation", + "type": "google.cloud.metastore_v1alpha.types.Federation" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "update_federation" + }, + "description": "Sample for UpdateFederation", + "file": "metastore_v1alpha_generated_dataproc_metastore_federation_update_federation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastoreFederation_UpdateFederation_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_federation_update_federation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationClient", + "shortName": "DataprocMetastoreFederationClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreFederationClient.update_federation", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation.UpdateFederation", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "UpdateFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.UpdateFederationRequest" + }, + { + "name": "federation", + "type": "google.cloud.metastore_v1alpha.types.Federation" + }, + { + "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.api_core.operation.Operation", + "shortName": "update_federation" + }, + "description": "Sample for UpdateFederation", + "file": "metastore_v1alpha_generated_dataproc_metastore_federation_update_federation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastoreFederation_UpdateFederation_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_federation_update_federation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.alter_metadata_resource_location", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.AlterMetadataResourceLocation", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "AlterMetadataResourceLocation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.AlterMetadataResourceLocationRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "alter_metadata_resource_location" + }, + "description": "Sample for AlterMetadataResourceLocation", + "file": "metastore_v1alpha_generated_dataproc_metastore_alter_metadata_resource_location_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_AlterMetadataResourceLocation_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_alter_metadata_resource_location_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.alter_metadata_resource_location", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.AlterMetadataResourceLocation", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "AlterMetadataResourceLocation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.AlterMetadataResourceLocationRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "alter_metadata_resource_location" + }, + "description": "Sample for AlterMetadataResourceLocation", + "file": "metastore_v1alpha_generated_dataproc_metastore_alter_metadata_resource_location_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_AlterMetadataResourceLocation_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_alter_metadata_resource_location_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.create_backup", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.CreateBackup", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "CreateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.CreateBackupRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup", + "type": "google.cloud.metastore_v1alpha.types.Backup" + }, + { + "name": "backup_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_backup" + }, + "description": "Sample for CreateBackup", + "file": "metastore_v1alpha_generated_dataproc_metastore_create_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_CreateBackup_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_create_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.create_backup", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.CreateBackup", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "CreateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.CreateBackupRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup", + "type": "google.cloud.metastore_v1alpha.types.Backup" + }, + { + "name": "backup_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_backup" + }, + "description": "Sample for CreateBackup", + "file": "metastore_v1alpha_generated_dataproc_metastore_create_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_CreateBackup_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_create_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.create_metadata_import", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.CreateMetadataImport", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "CreateMetadataImport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.CreateMetadataImportRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "metadata_import", + "type": "google.cloud.metastore_v1alpha.types.MetadataImport" + }, + { + "name": "metadata_import_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_metadata_import" + }, + "description": "Sample for CreateMetadataImport", + "file": "metastore_v1alpha_generated_dataproc_metastore_create_metadata_import_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_CreateMetadataImport_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_create_metadata_import_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.create_metadata_import", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.CreateMetadataImport", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "CreateMetadataImport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.CreateMetadataImportRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "metadata_import", + "type": "google.cloud.metastore_v1alpha.types.MetadataImport" + }, + { + "name": "metadata_import_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_metadata_import" + }, + "description": "Sample for CreateMetadataImport", + "file": "metastore_v1alpha_generated_dataproc_metastore_create_metadata_import_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_CreateMetadataImport_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_create_metadata_import_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.create_service", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.CreateService", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "CreateService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.CreateServiceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "service", + "type": "google.cloud.metastore_v1alpha.types.Service" + }, + { + "name": "service_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_service" + }, + "description": "Sample for CreateService", + "file": "metastore_v1alpha_generated_dataproc_metastore_create_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_CreateService_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_create_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.create_service", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.CreateService", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "CreateService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.CreateServiceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "service", + "type": "google.cloud.metastore_v1alpha.types.Service" + }, + { + "name": "service_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_service" + }, + "description": "Sample for CreateService", + "file": "metastore_v1alpha_generated_dataproc_metastore_create_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_CreateService_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_create_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.delete_backup", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.DeleteBackup", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.DeleteBackupRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "delete_backup" + }, + "description": "Sample for DeleteBackup", + "file": "metastore_v1alpha_generated_dataproc_metastore_delete_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_DeleteBackup_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_delete_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.delete_backup", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.DeleteBackup", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.DeleteBackupRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "delete_backup" + }, + "description": "Sample for DeleteBackup", + "file": "metastore_v1alpha_generated_dataproc_metastore_delete_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_DeleteBackup_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_delete_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.delete_service", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.DeleteService", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "DeleteService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.DeleteServiceRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "delete_service" + }, + "description": "Sample for DeleteService", + "file": "metastore_v1alpha_generated_dataproc_metastore_delete_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_DeleteService_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_delete_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.delete_service", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.DeleteService", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "DeleteService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.DeleteServiceRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "delete_service" + }, + "description": "Sample for DeleteService", + "file": "metastore_v1alpha_generated_dataproc_metastore_delete_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_DeleteService_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_delete_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.export_metadata", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.ExportMetadata", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ExportMetadata" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.ExportMetadataRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "export_metadata" + }, + "description": "Sample for ExportMetadata", + "file": "metastore_v1alpha_generated_dataproc_metastore_export_metadata_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_ExportMetadata_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_export_metadata_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.export_metadata", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.ExportMetadata", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ExportMetadata" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.ExportMetadataRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "export_metadata" + }, + "description": "Sample for ExportMetadata", + "file": "metastore_v1alpha_generated_dataproc_metastore_export_metadata_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_ExportMetadata_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_export_metadata_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.get_backup", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.GetBackup", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.GetBackupRequest" + }, + { + "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.metastore_v1alpha.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "metastore_v1alpha_generated_dataproc_metastore_get_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_GetBackup_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": "metastore_v1alpha_generated_dataproc_metastore_get_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.get_backup", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.GetBackup", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.GetBackupRequest" + }, + { + "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.metastore_v1alpha.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "metastore_v1alpha_generated_dataproc_metastore_get_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_GetBackup_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": "metastore_v1alpha_generated_dataproc_metastore_get_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.get_metadata_import", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.GetMetadataImport", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "GetMetadataImport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.GetMetadataImportRequest" + }, + { + "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.metastore_v1alpha.types.MetadataImport", + "shortName": "get_metadata_import" + }, + "description": "Sample for GetMetadataImport", + "file": "metastore_v1alpha_generated_dataproc_metastore_get_metadata_import_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_GetMetadataImport_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": "metastore_v1alpha_generated_dataproc_metastore_get_metadata_import_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.get_metadata_import", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.GetMetadataImport", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "GetMetadataImport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.GetMetadataImportRequest" + }, + { + "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.metastore_v1alpha.types.MetadataImport", + "shortName": "get_metadata_import" + }, + "description": "Sample for GetMetadataImport", + "file": "metastore_v1alpha_generated_dataproc_metastore_get_metadata_import_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_GetMetadataImport_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": "metastore_v1alpha_generated_dataproc_metastore_get_metadata_import_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.get_service", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.GetService", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "GetService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.GetServiceRequest" + }, + { + "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.metastore_v1alpha.types.Service", + "shortName": "get_service" + }, + "description": "Sample for GetService", + "file": "metastore_v1alpha_generated_dataproc_metastore_get_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_GetService_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": "metastore_v1alpha_generated_dataproc_metastore_get_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.get_service", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.GetService", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "GetService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.GetServiceRequest" + }, + { + "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.metastore_v1alpha.types.Service", + "shortName": "get_service" + }, + "description": "Sample for GetService", + "file": "metastore_v1alpha_generated_dataproc_metastore_get_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_GetService_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": "metastore_v1alpha_generated_dataproc_metastore_get_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.list_backups", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.ListBackups", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ListBackups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.ListBackupsRequest" + }, + { + "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.metastore_v1alpha.services.dataproc_metastore.pagers.ListBackupsAsyncPager", + "shortName": "list_backups" + }, + "description": "Sample for ListBackups", + "file": "metastore_v1alpha_generated_dataproc_metastore_list_backups_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_ListBackups_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": "metastore_v1alpha_generated_dataproc_metastore_list_backups_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.list_backups", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.ListBackups", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ListBackups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.ListBackupsRequest" + }, + { + "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.metastore_v1alpha.services.dataproc_metastore.pagers.ListBackupsPager", + "shortName": "list_backups" + }, + "description": "Sample for ListBackups", + "file": "metastore_v1alpha_generated_dataproc_metastore_list_backups_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_ListBackups_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": "metastore_v1alpha_generated_dataproc_metastore_list_backups_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.list_metadata_imports", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.ListMetadataImports", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ListMetadataImports" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.ListMetadataImportsRequest" + }, + { + "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.metastore_v1alpha.services.dataproc_metastore.pagers.ListMetadataImportsAsyncPager", + "shortName": "list_metadata_imports" + }, + "description": "Sample for ListMetadataImports", + "file": "metastore_v1alpha_generated_dataproc_metastore_list_metadata_imports_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_ListMetadataImports_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": "metastore_v1alpha_generated_dataproc_metastore_list_metadata_imports_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.list_metadata_imports", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.ListMetadataImports", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ListMetadataImports" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.ListMetadataImportsRequest" + }, + { + "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.metastore_v1alpha.services.dataproc_metastore.pagers.ListMetadataImportsPager", + "shortName": "list_metadata_imports" + }, + "description": "Sample for ListMetadataImports", + "file": "metastore_v1alpha_generated_dataproc_metastore_list_metadata_imports_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_ListMetadataImports_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": "metastore_v1alpha_generated_dataproc_metastore_list_metadata_imports_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.list_services", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.ListServices", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ListServices" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.ListServicesRequest" + }, + { + "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.metastore_v1alpha.services.dataproc_metastore.pagers.ListServicesAsyncPager", + "shortName": "list_services" + }, + "description": "Sample for ListServices", + "file": "metastore_v1alpha_generated_dataproc_metastore_list_services_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_ListServices_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": "metastore_v1alpha_generated_dataproc_metastore_list_services_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.list_services", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.ListServices", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ListServices" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.ListServicesRequest" + }, + { + "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.metastore_v1alpha.services.dataproc_metastore.pagers.ListServicesPager", + "shortName": "list_services" + }, + "description": "Sample for ListServices", + "file": "metastore_v1alpha_generated_dataproc_metastore_list_services_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_ListServices_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": "metastore_v1alpha_generated_dataproc_metastore_list_services_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.move_table_to_database", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.MoveTableToDatabase", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "MoveTableToDatabase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.MoveTableToDatabaseRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "move_table_to_database" + }, + "description": "Sample for MoveTableToDatabase", + "file": "metastore_v1alpha_generated_dataproc_metastore_move_table_to_database_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_MoveTableToDatabase_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_move_table_to_database_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.move_table_to_database", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.MoveTableToDatabase", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "MoveTableToDatabase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.MoveTableToDatabaseRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "move_table_to_database" + }, + "description": "Sample for MoveTableToDatabase", + "file": "metastore_v1alpha_generated_dataproc_metastore_move_table_to_database_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_MoveTableToDatabase_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_move_table_to_database_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.query_metadata", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.QueryMetadata", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "QueryMetadata" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.QueryMetadataRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "query_metadata" + }, + "description": "Sample for QueryMetadata", + "file": "metastore_v1alpha_generated_dataproc_metastore_query_metadata_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_QueryMetadata_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_query_metadata_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.query_metadata", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.QueryMetadata", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "QueryMetadata" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.QueryMetadataRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "query_metadata" + }, + "description": "Sample for QueryMetadata", + "file": "metastore_v1alpha_generated_dataproc_metastore_query_metadata_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_QueryMetadata_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_query_metadata_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.remove_iam_policy", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.RemoveIamPolicy", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "RemoveIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.RemoveIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.metastore_v1alpha.types.RemoveIamPolicyResponse", + "shortName": "remove_iam_policy" + }, + "description": "Sample for RemoveIamPolicy", + "file": "metastore_v1alpha_generated_dataproc_metastore_remove_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_RemoveIamPolicy_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": "metastore_v1alpha_generated_dataproc_metastore_remove_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.remove_iam_policy", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.RemoveIamPolicy", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "RemoveIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.RemoveIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.metastore_v1alpha.types.RemoveIamPolicyResponse", + "shortName": "remove_iam_policy" + }, + "description": "Sample for RemoveIamPolicy", + "file": "metastore_v1alpha_generated_dataproc_metastore_remove_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_RemoveIamPolicy_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": "metastore_v1alpha_generated_dataproc_metastore_remove_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.restore_service", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.RestoreService", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "RestoreService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.RestoreServiceRequest" + }, + { + "name": "service", + "type": "str" + }, + { + "name": "backup", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "restore_service" + }, + "description": "Sample for RestoreService", + "file": "metastore_v1alpha_generated_dataproc_metastore_restore_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_RestoreService_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_restore_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.restore_service", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.RestoreService", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "RestoreService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.RestoreServiceRequest" + }, + { + "name": "service", + "type": "str" + }, + { + "name": "backup", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "restore_service" + }, + "description": "Sample for RestoreService", + "file": "metastore_v1alpha_generated_dataproc_metastore_restore_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_RestoreService_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_restore_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.update_metadata_import", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.UpdateMetadataImport", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "UpdateMetadataImport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.UpdateMetadataImportRequest" + }, + { + "name": "metadata_import", + "type": "google.cloud.metastore_v1alpha.types.MetadataImport" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "update_metadata_import" + }, + "description": "Sample for UpdateMetadataImport", + "file": "metastore_v1alpha_generated_dataproc_metastore_update_metadata_import_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_UpdateMetadataImport_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_update_metadata_import_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.update_metadata_import", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.UpdateMetadataImport", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "UpdateMetadataImport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.UpdateMetadataImportRequest" + }, + { + "name": "metadata_import", + "type": "google.cloud.metastore_v1alpha.types.MetadataImport" + }, + { + "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.api_core.operation.Operation", + "shortName": "update_metadata_import" + }, + "description": "Sample for UpdateMetadataImport", + "file": "metastore_v1alpha_generated_dataproc_metastore_update_metadata_import_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_UpdateMetadataImport_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_update_metadata_import_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreAsyncClient.update_service", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.UpdateService", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "UpdateService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.UpdateServiceRequest" + }, + { + "name": "service", + "type": "google.cloud.metastore_v1alpha.types.Service" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "update_service" + }, + "description": "Sample for UpdateService", + "file": "metastore_v1alpha_generated_dataproc_metastore_update_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_UpdateService_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_update_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1alpha.DataprocMetastoreClient.update_service", + "method": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore.UpdateService", + "service": { + "fullName": "google.cloud.metastore.v1alpha.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "UpdateService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1alpha.types.UpdateServiceRequest" + }, + { + "name": "service", + "type": "google.cloud.metastore_v1alpha.types.Service" + }, + { + "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.api_core.operation.Operation", + "shortName": "update_service" + }, + "description": "Sample for UpdateService", + "file": "metastore_v1alpha_generated_dataproc_metastore_update_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1alpha_generated_DataprocMetastore_UpdateService_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1alpha_generated_dataproc_metastore_update_service_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1alpha/scripts/fixup_metastore_v1alpha_keywords.py b/owl-bot-staging/v1alpha/scripts/fixup_metastore_v1alpha_keywords.py new file mode 100644 index 0000000..418ffb6 --- /dev/null +++ b/owl-bot-staging/v1alpha/scripts/fixup_metastore_v1alpha_keywords.py @@ -0,0 +1,199 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class metastoreCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'alter_metadata_resource_location': ('service', 'resource_name', 'location_uri', ), + 'create_backup': ('parent', 'backup_id', 'backup', 'request_id', ), + 'create_federation': ('parent', 'federation_id', 'federation', 'request_id', ), + 'create_metadata_import': ('parent', 'metadata_import_id', 'metadata_import', 'request_id', ), + 'create_service': ('parent', 'service_id', 'service', 'request_id', ), + 'delete_backup': ('name', 'request_id', ), + 'delete_federation': ('name', 'request_id', ), + 'delete_service': ('name', 'request_id', ), + 'export_metadata': ('service', 'destination_gcs_folder', 'request_id', 'database_dump_type', ), + 'get_backup': ('name', ), + 'get_federation': ('name', ), + 'get_metadata_import': ('name', ), + 'get_service': ('name', ), + 'list_backups': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_federations': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_metadata_imports': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_services': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'move_table_to_database': ('service', 'table_name', 'db_name', 'destination_db_name', ), + 'query_metadata': ('service', 'query', ), + 'remove_iam_policy': ('resource', 'asynchronous', ), + 'restore_service': ('service', 'backup', 'restore_type', 'request_id', ), + 'update_federation': ('update_mask', 'federation', 'request_id', ), + 'update_metadata_import': ('update_mask', 'metadata_import', 'request_id', ), + 'update_service': ('update_mask', 'service', '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=metastoreCallTransformer(), +): + """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 metastore client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1alpha/setup.py b/owl-bot-staging/v1alpha/setup.py new file mode 100644 index 0000000..3b0acfa --- /dev/null +++ b/owl-bot-staging/v1alpha/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-dataproc-metastore' + + +description = "Google Cloud Dataproc Metastore API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/metastore/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", + "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", +] +url = "https://github.com/googleapis/python-dataproc-metastore" + +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/v1alpha/testing/constraints-3.10.txt b/owl-bot-staging/v1alpha/testing/constraints-3.10.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1alpha/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1alpha/testing/constraints-3.11.txt b/owl-bot-staging/v1alpha/testing/constraints-3.11.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1alpha/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1alpha/testing/constraints-3.12.txt b/owl-bot-staging/v1alpha/testing/constraints-3.12.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1alpha/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1alpha/testing/constraints-3.7.txt b/owl-bot-staging/v1alpha/testing/constraints-3.7.txt new file mode 100644 index 0000000..2beecf9 --- /dev/null +++ b/owl-bot-staging/v1alpha/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 +grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/v1alpha/testing/constraints-3.8.txt b/owl-bot-staging/v1alpha/testing/constraints-3.8.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1alpha/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1alpha/testing/constraints-3.9.txt b/owl-bot-staging/v1alpha/testing/constraints-3.9.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1alpha/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1alpha/tests/__init__.py b/owl-bot-staging/v1alpha/tests/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1alpha/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1alpha/tests/unit/__init__.py b/owl-bot-staging/v1alpha/tests/unit/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1alpha/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1alpha/tests/unit/gapic/metastore_v1alpha/__init__.py b/owl-bot-staging/v1alpha/tests/unit/gapic/metastore_v1alpha/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1alpha/tests/unit/gapic/metastore_v1alpha/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1alpha/tests/unit/gapic/metastore_v1alpha/test_dataproc_metastore.py b/owl-bot-staging/v1alpha/tests/unit/gapic/metastore_v1alpha/test_dataproc_metastore.py new file mode 100644 index 0000000..28ebb18 --- /dev/null +++ b/owl-bot-staging/v1alpha/tests/unit/gapic/metastore_v1alpha/test_dataproc_metastore.py @@ -0,0 +1,12069 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.metastore_v1alpha.services.dataproc_metastore import DataprocMetastoreAsyncClient +from google.cloud.metastore_v1alpha.services.dataproc_metastore import DataprocMetastoreClient +from google.cloud.metastore_v1alpha.services.dataproc_metastore import pagers +from google.cloud.metastore_v1alpha.services.dataproc_metastore import transports +from google.cloud.metastore_v1alpha.types import metastore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import dayofweek_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 DataprocMetastoreClient._get_default_mtls_endpoint(None) is None + assert DataprocMetastoreClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DataprocMetastoreClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DataprocMetastoreClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DataprocMetastoreClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DataprocMetastoreClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DataprocMetastoreClient, "grpc"), + (DataprocMetastoreAsyncClient, "grpc_asyncio"), + (DataprocMetastoreClient, "rest"), +]) +def test_dataproc_metastore_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 == ( + 'metastore.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://metastore.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DataprocMetastoreGrpcTransport, "grpc"), + (transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DataprocMetastoreRestTransport, "rest"), +]) +def test_dataproc_metastore_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", [ + (DataprocMetastoreClient, "grpc"), + (DataprocMetastoreAsyncClient, "grpc_asyncio"), + (DataprocMetastoreClient, "rest"), +]) +def test_dataproc_metastore_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 == ( + 'metastore.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://metastore.googleapis.com' + ) + + +def test_dataproc_metastore_client_get_transport_class(): + transport = DataprocMetastoreClient.get_transport_class() + available_transports = [ + transports.DataprocMetastoreGrpcTransport, + transports.DataprocMetastoreRestTransport, + ] + assert transport in available_transports + + transport = DataprocMetastoreClient.get_transport_class("grpc") + assert transport == transports.DataprocMetastoreGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport, "grpc"), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio"), + (DataprocMetastoreClient, transports.DataprocMetastoreRestTransport, "rest"), +]) +@mock.patch.object(DataprocMetastoreClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreClient)) +@mock.patch.object(DataprocMetastoreAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreAsyncClient)) +def test_dataproc_metastore_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(DataprocMetastoreClient, '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(DataprocMetastoreClient, '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", [ + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport, "grpc", "true"), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport, "grpc", "false"), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (DataprocMetastoreClient, transports.DataprocMetastoreRestTransport, "rest", "true"), + (DataprocMetastoreClient, transports.DataprocMetastoreRestTransport, "rest", "false"), +]) +@mock.patch.object(DataprocMetastoreClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreClient)) +@mock.patch.object(DataprocMetastoreAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_dataproc_metastore_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", [ + DataprocMetastoreClient, DataprocMetastoreAsyncClient +]) +@mock.patch.object(DataprocMetastoreClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreClient)) +@mock.patch.object(DataprocMetastoreAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreAsyncClient)) +def test_dataproc_metastore_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", [ + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport, "grpc"), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio"), + (DataprocMetastoreClient, transports.DataprocMetastoreRestTransport, "rest"), +]) +def test_dataproc_metastore_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", [ + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport, "grpc", grpc_helpers), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (DataprocMetastoreClient, transports.DataprocMetastoreRestTransport, "rest", None), +]) +def test_dataproc_metastore_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_dataproc_metastore_client_client_options_from_dict(): + with mock.patch('google.cloud.metastore_v1alpha.services.dataproc_metastore.transports.DataprocMetastoreGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DataprocMetastoreClient( + 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", [ + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport, "grpc", grpc_helpers), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_dataproc_metastore_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( + "metastore.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="metastore.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ListServicesRequest, + dict, +]) +def test_list_services(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListServicesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListServicesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_services_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_services), + '__call__') as call: + client.list_services() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListServicesRequest() + +@pytest.mark.asyncio +async def test_list_services_async(transport: str = 'grpc_asyncio', request_type=metastore.ListServicesRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListServicesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListServicesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_services_async_from_dict(): + await test_list_services_async(request_type=dict) + + +def test_list_services_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ListServicesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + call.return_value = metastore.ListServicesResponse() + client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_services_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ListServicesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListServicesResponse()) + await client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_services_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListServicesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_services( + 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_services_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_services( + metastore.ListServicesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_services_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListServicesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListServicesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_services( + 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_services_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_services( + metastore.ListServicesRequest(), + parent='parent_value', + ) + + +def test_list_services_pager(transport_name: str = "grpc"): + client = DataprocMetastoreClient( + 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_services), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + metastore.Service(), + ], + next_page_token='abc', + ), + metastore.ListServicesResponse( + services=[], + next_page_token='def', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + ], + next_page_token='ghi', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_services(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore.Service) + for i in results) +def test_list_services_pages(transport_name: str = "grpc"): + client = DataprocMetastoreClient( + 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_services), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + metastore.Service(), + ], + next_page_token='abc', + ), + metastore.ListServicesResponse( + services=[], + next_page_token='def', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + ], + next_page_token='ghi', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + ], + ), + RuntimeError, + ) + pages = list(client.list_services(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_services_async_pager(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + metastore.Service(), + ], + next_page_token='abc', + ), + metastore.ListServicesResponse( + services=[], + next_page_token='def', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + ], + next_page_token='ghi', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_services(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, metastore.Service) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_services_async_pages(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + metastore.Service(), + ], + next_page_token='abc', + ), + metastore.ListServicesResponse( + services=[], + next_page_token='def', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + ], + next_page_token='ghi', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_services(request={})).pages: # pragma: no branch + 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", [ + metastore.GetServiceRequest, + dict, +]) +def test_get_service(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.Service( + name='name_value', + network='network_value', + endpoint_uri='endpoint_uri_value', + port=453, + state=metastore.Service.State.CREATING, + state_message='state_message_value', + artifact_gcs_uri='artifact_gcs_uri_value', + tier=metastore.Service.Tier.DEVELOPER, + uid='uid_value', + release_channel=metastore.Service.ReleaseChannel.CANARY, + database_type=metastore.Service.DatabaseType.MYSQL, + hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value'), + ) + response = client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.Service) + assert response.name == 'name_value' + assert response.network == 'network_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.port == 453 + assert response.state == metastore.Service.State.CREATING + assert response.state_message == 'state_message_value' + assert response.artifact_gcs_uri == 'artifact_gcs_uri_value' + assert response.tier == metastore.Service.Tier.DEVELOPER + assert response.uid == 'uid_value' + assert response.release_channel == metastore.Service.ReleaseChannel.CANARY + assert response.database_type == metastore.Service.DatabaseType.MYSQL + + +def test_get_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_service), + '__call__') as call: + client.get_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetServiceRequest() + +@pytest.mark.asyncio +async def test_get_service_async(transport: str = 'grpc_asyncio', request_type=metastore.GetServiceRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.Service( + name='name_value', + network='network_value', + endpoint_uri='endpoint_uri_value', + port=453, + state=metastore.Service.State.CREATING, + state_message='state_message_value', + artifact_gcs_uri='artifact_gcs_uri_value', + tier=metastore.Service.Tier.DEVELOPER, + uid='uid_value', + release_channel=metastore.Service.ReleaseChannel.CANARY, + database_type=metastore.Service.DatabaseType.MYSQL, + )) + response = await client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.Service) + assert response.name == 'name_value' + assert response.network == 'network_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.port == 453 + assert response.state == metastore.Service.State.CREATING + assert response.state_message == 'state_message_value' + assert response.artifact_gcs_uri == 'artifact_gcs_uri_value' + assert response.tier == metastore.Service.Tier.DEVELOPER + assert response.uid == 'uid_value' + assert response.release_channel == metastore.Service.ReleaseChannel.CANARY + assert response.database_type == metastore.Service.DatabaseType.MYSQL + + +@pytest.mark.asyncio +async def test_get_service_async_from_dict(): + await test_get_service_async(request_type=dict) + + +def test_get_service_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.GetServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + call.return_value = metastore.Service() + client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_service_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.GetServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.Service()) + await client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_service_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.Service() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_service( + 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_service_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_service( + metastore.GetServiceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_service_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.Service() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.Service()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_service( + 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_service_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_service( + metastore.GetServiceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.CreateServiceRequest, + dict, +]) +def test_create_service(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_service), + '__call__') as call: + client.create_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateServiceRequest() + +@pytest.mark.asyncio +async def test_create_service_async(transport: str = 'grpc_asyncio', request_type=metastore.CreateServiceRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_service_async_from_dict(): + await test_create_service_async(request_type=dict) + + +def test_create_service_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.CreateServiceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_service_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.CreateServiceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_service_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_service( + parent='parent_value', + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + service_id='service_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].service + mock_val = metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')) + assert arg == mock_val + arg = args[0].service_id + mock_val = 'service_id_value' + assert arg == mock_val + + +def test_create_service_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_service( + metastore.CreateServiceRequest(), + parent='parent_value', + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + service_id='service_id_value', + ) + +@pytest.mark.asyncio +async def test_create_service_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_service( + parent='parent_value', + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + service_id='service_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].service + mock_val = metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')) + assert arg == mock_val + arg = args[0].service_id + mock_val = 'service_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_service_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_service( + metastore.CreateServiceRequest(), + parent='parent_value', + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + service_id='service_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.UpdateServiceRequest, + dict, +]) +def test_update_service(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.UpdateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_service), + '__call__') as call: + client.update_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.UpdateServiceRequest() + +@pytest.mark.asyncio +async def test_update_service_async(transport: str = 'grpc_asyncio', request_type=metastore.UpdateServiceRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.UpdateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_service_async_from_dict(): + await test_update_service_async(request_type=dict) + + +def test_update_service_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.UpdateServiceRequest() + + request.service.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_service_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.UpdateServiceRequest() + + request.service.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service.name=name_value', + ) in kw['metadata'] + + +def test_update_service_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_service( + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_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].service + mock_val = metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_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_service_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_service( + metastore.UpdateServiceRequest(), + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_service_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_service( + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_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].service + mock_val = metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_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_service_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_service( + metastore.UpdateServiceRequest(), + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.DeleteServiceRequest, + dict, +]) +def test_delete_service(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.DeleteServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_service), + '__call__') as call: + client.delete_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.DeleteServiceRequest() + +@pytest.mark.asyncio +async def test_delete_service_async(transport: str = 'grpc_asyncio', request_type=metastore.DeleteServiceRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.DeleteServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_service_async_from_dict(): + await test_delete_service_async(request_type=dict) + + +def test_delete_service_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.DeleteServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_service_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.DeleteServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_service_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_service( + 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_service_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_service( + metastore.DeleteServiceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_service_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_service( + 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_service_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_service( + metastore.DeleteServiceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ListMetadataImportsRequest, + dict, +]) +def test_list_metadata_imports(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata_imports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListMetadataImportsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_metadata_imports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListMetadataImportsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMetadataImportsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_metadata_imports_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_metadata_imports), + '__call__') as call: + client.list_metadata_imports() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListMetadataImportsRequest() + +@pytest.mark.asyncio +async def test_list_metadata_imports_async(transport: str = 'grpc_asyncio', request_type=metastore.ListMetadataImportsRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata_imports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListMetadataImportsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_metadata_imports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListMetadataImportsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMetadataImportsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_metadata_imports_async_from_dict(): + await test_list_metadata_imports_async(request_type=dict) + + +def test_list_metadata_imports_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ListMetadataImportsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_metadata_imports), + '__call__') as call: + call.return_value = metastore.ListMetadataImportsResponse() + client.list_metadata_imports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_metadata_imports_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ListMetadataImportsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_metadata_imports), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListMetadataImportsResponse()) + await client.list_metadata_imports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_metadata_imports_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_metadata_imports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListMetadataImportsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_metadata_imports( + 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_metadata_imports_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_metadata_imports( + metastore.ListMetadataImportsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_metadata_imports_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_metadata_imports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListMetadataImportsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListMetadataImportsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_metadata_imports( + 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_metadata_imports_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_metadata_imports( + metastore.ListMetadataImportsRequest(), + parent='parent_value', + ) + + +def test_list_metadata_imports_pager(transport_name: str = "grpc"): + client = DataprocMetastoreClient( + 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_metadata_imports), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + next_page_token='abc', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[], + next_page_token='def', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + ], + next_page_token='ghi', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_metadata_imports(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore.MetadataImport) + for i in results) +def test_list_metadata_imports_pages(transport_name: str = "grpc"): + client = DataprocMetastoreClient( + 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_metadata_imports), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + next_page_token='abc', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[], + next_page_token='def', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + ], + next_page_token='ghi', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + ), + RuntimeError, + ) + pages = list(client.list_metadata_imports(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_metadata_imports_async_pager(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_metadata_imports), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + next_page_token='abc', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[], + next_page_token='def', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + ], + next_page_token='ghi', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_metadata_imports(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, metastore.MetadataImport) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_metadata_imports_async_pages(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_metadata_imports), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + next_page_token='abc', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[], + next_page_token='def', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + ], + next_page_token='ghi', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_metadata_imports(request={})).pages: # pragma: no branch + 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", [ + metastore.GetMetadataImportRequest, + dict, +]) +def test_get_metadata_import(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.MetadataImport( + name='name_value', + description='description_value', + state=metastore.MetadataImport.State.RUNNING, + database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL), + ) + response = client.get_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetMetadataImportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.MetadataImport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == metastore.MetadataImport.State.RUNNING + + +def test_get_metadata_import_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + client.get_metadata_import() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetMetadataImportRequest() + +@pytest.mark.asyncio +async def test_get_metadata_import_async(transport: str = 'grpc_asyncio', request_type=metastore.GetMetadataImportRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.MetadataImport( + name='name_value', + description='description_value', + state=metastore.MetadataImport.State.RUNNING, + )) + response = await client.get_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetMetadataImportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.MetadataImport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == metastore.MetadataImport.State.RUNNING + + +@pytest.mark.asyncio +async def test_get_metadata_import_async_from_dict(): + await test_get_metadata_import_async(request_type=dict) + + +def test_get_metadata_import_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.GetMetadataImportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + call.return_value = metastore.MetadataImport() + client.get_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_metadata_import_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.GetMetadataImportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.MetadataImport()) + await client.get_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_metadata_import_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.MetadataImport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_metadata_import( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_metadata_import_flattened_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_metadata_import( + metastore.GetMetadataImportRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_metadata_import_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.MetadataImport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.MetadataImport()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_metadata_import( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_metadata_import_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_metadata_import( + metastore.GetMetadataImportRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.CreateMetadataImportRequest, + dict, +]) +def test_create_metadata_import(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateMetadataImportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_metadata_import_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_metadata_import), + '__call__') as call: + client.create_metadata_import() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateMetadataImportRequest() + +@pytest.mark.asyncio +async def test_create_metadata_import_async(transport: str = 'grpc_asyncio', request_type=metastore.CreateMetadataImportRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateMetadataImportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_metadata_import_async_from_dict(): + await test_create_metadata_import_async(request_type=dict) + + +def test_create_metadata_import_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.CreateMetadataImportRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_metadata_import), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_metadata_import_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.CreateMetadataImportRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_metadata_import), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_metadata_import_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_metadata_import( + parent='parent_value', + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + metadata_import_id='metadata_import_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].metadata_import + mock_val = metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)) + assert arg == mock_val + arg = args[0].metadata_import_id + mock_val = 'metadata_import_id_value' + assert arg == mock_val + + +def test_create_metadata_import_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_metadata_import( + metastore.CreateMetadataImportRequest(), + parent='parent_value', + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + metadata_import_id='metadata_import_id_value', + ) + +@pytest.mark.asyncio +async def test_create_metadata_import_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_metadata_import( + parent='parent_value', + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + metadata_import_id='metadata_import_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].metadata_import + mock_val = metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)) + assert arg == mock_val + arg = args[0].metadata_import_id + mock_val = 'metadata_import_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_metadata_import_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_metadata_import( + metastore.CreateMetadataImportRequest(), + parent='parent_value', + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + metadata_import_id='metadata_import_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.UpdateMetadataImportRequest, + dict, +]) +def test_update_metadata_import(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.UpdateMetadataImportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_metadata_import_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_metadata_import), + '__call__') as call: + client.update_metadata_import() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.UpdateMetadataImportRequest() + +@pytest.mark.asyncio +async def test_update_metadata_import_async(transport: str = 'grpc_asyncio', request_type=metastore.UpdateMetadataImportRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.UpdateMetadataImportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_metadata_import_async_from_dict(): + await test_update_metadata_import_async(request_type=dict) + + +def test_update_metadata_import_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.UpdateMetadataImportRequest() + + request.metadata_import.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_metadata_import), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'metadata_import.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_metadata_import_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.UpdateMetadataImportRequest() + + request.metadata_import.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_metadata_import), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'metadata_import.name=name_value', + ) in kw['metadata'] + + +def test_update_metadata_import_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_metadata_import( + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + 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].metadata_import + mock_val = metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)) + 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_metadata_import_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_metadata_import( + metastore.UpdateMetadataImportRequest(), + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_metadata_import_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_metadata_import( + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + 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].metadata_import + mock_val = metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)) + 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_metadata_import_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_metadata_import( + metastore.UpdateMetadataImportRequest(), + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ExportMetadataRequest, + dict, +]) +def test_export_metadata(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.export_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ExportMetadataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_metadata_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_metadata), + '__call__') as call: + client.export_metadata() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ExportMetadataRequest() + +@pytest.mark.asyncio +async def test_export_metadata_async(transport: str = 'grpc_asyncio', request_type=metastore.ExportMetadataRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.export_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ExportMetadataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_export_metadata_async_from_dict(): + await test_export_metadata_async(request_type=dict) + + +def test_export_metadata_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ExportMetadataRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_metadata), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.export_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_export_metadata_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ExportMetadataRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_metadata), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.export_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + metastore.RestoreServiceRequest, + dict, +]) +def test_restore_service(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.restore_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.RestoreServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_restore_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + client.restore_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.RestoreServiceRequest() + +@pytest.mark.asyncio +async def test_restore_service_async(transport: str = 'grpc_asyncio', request_type=metastore.RestoreServiceRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.restore_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.RestoreServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_restore_service_async_from_dict(): + await test_restore_service_async(request_type=dict) + + +def test_restore_service_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.RestoreServiceRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.restore_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_restore_service_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.RestoreServiceRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.restore_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +def test_restore_service_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.restore_service( + service='service_value', + backup='backup_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].service + mock_val = 'service_value' + assert arg == mock_val + arg = args[0].backup + mock_val = 'backup_value' + assert arg == mock_val + + +def test_restore_service_flattened_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restore_service( + metastore.RestoreServiceRequest(), + service='service_value', + backup='backup_value', + ) + +@pytest.mark.asyncio +async def test_restore_service_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.restore_service( + service='service_value', + backup='backup_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].service + mock_val = 'service_value' + assert arg == mock_val + arg = args[0].backup + mock_val = 'backup_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_restore_service_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.restore_service( + metastore.RestoreServiceRequest(), + service='service_value', + backup='backup_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ListBackupsRequest, + dict, +]) +def test_list_backups(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListBackupsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListBackupsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_backups_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_backups), + '__call__') as call: + client.list_backups() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListBackupsRequest() + +@pytest.mark.asyncio +async def test_list_backups_async(transport: str = 'grpc_asyncio', request_type=metastore.ListBackupsRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListBackupsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListBackupsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_backups_async_from_dict(): + await test_list_backups_async(request_type=dict) + + +def test_list_backups_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ListBackupsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), + '__call__') as call: + call.return_value = metastore.ListBackupsResponse() + client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backups_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ListBackupsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListBackupsResponse()) + await client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backups_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListBackupsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_backups( + 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_backups_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_backups( + metastore.ListBackupsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_backups_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListBackupsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListBackupsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_backups( + 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_backups_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_backups( + metastore.ListBackupsRequest(), + parent='parent_value', + ) + + +def test_list_backups_pager(transport_name: str = "grpc"): + client = DataprocMetastoreClient( + 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_backups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + metastore.Backup(), + ], + next_page_token='abc', + ), + metastore.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + ], + next_page_token='ghi', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_backups(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore.Backup) + for i in results) +def test_list_backups_pages(transport_name: str = "grpc"): + client = DataprocMetastoreClient( + 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_backups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + metastore.Backup(), + ], + next_page_token='abc', + ), + metastore.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + ], + next_page_token='ghi', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + ], + ), + RuntimeError, + ) + pages = list(client.list_backups(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_backups_async_pager(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + metastore.Backup(), + ], + next_page_token='abc', + ), + metastore.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + ], + next_page_token='ghi', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_backups(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, metastore.Backup) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_backups_async_pages(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + metastore.Backup(), + ], + next_page_token='abc', + ), + metastore.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + ], + next_page_token='ghi', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_backups(request={})).pages: # pragma: no branch + 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", [ + metastore.GetBackupRequest, + dict, +]) +def test_get_backup(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.Backup( + name='name_value', + state=metastore.Backup.State.CREATING, + description='description_value', + restoring_services=['restoring_services_value'], + ) + response = client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.Backup) + assert response.name == 'name_value' + assert response.state == metastore.Backup.State.CREATING + assert response.description == 'description_value' + assert response.restoring_services == ['restoring_services_value'] + + +def test_get_backup_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_backup), + '__call__') as call: + client.get_backup() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetBackupRequest() + +@pytest.mark.asyncio +async def test_get_backup_async(transport: str = 'grpc_asyncio', request_type=metastore.GetBackupRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.Backup( + name='name_value', + state=metastore.Backup.State.CREATING, + description='description_value', + restoring_services=['restoring_services_value'], + )) + response = await client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.Backup) + assert response.name == 'name_value' + assert response.state == metastore.Backup.State.CREATING + assert response.description == 'description_value' + assert response.restoring_services == ['restoring_services_value'] + + +@pytest.mark.asyncio +async def test_get_backup_async_from_dict(): + await test_get_backup_async(request_type=dict) + + +def test_get_backup_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.GetBackupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup), + '__call__') as call: + call.return_value = metastore.Backup() + client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backup_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.GetBackupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.Backup()) + await client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backup_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.Backup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_backup( + 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_backup_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_backup( + metastore.GetBackupRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_backup_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.Backup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.Backup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_backup( + 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_backup_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_backup( + metastore.GetBackupRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.CreateBackupRequest, + dict, +]) +def test_create_backup(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_backup_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_backup), + '__call__') as call: + client.create_backup() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateBackupRequest() + +@pytest.mark.asyncio +async def test_create_backup_async(transport: str = 'grpc_asyncio', request_type=metastore.CreateBackupRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_backup_async_from_dict(): + await test_create_backup_async(request_type=dict) + + +def test_create_backup_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.CreateBackupRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backup_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.CreateBackupRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backup_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_backup( + parent='parent_value', + backup=metastore.Backup(name='name_value'), + backup_id='backup_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].backup + mock_val = metastore.Backup(name='name_value') + assert arg == mock_val + arg = args[0].backup_id + mock_val = 'backup_id_value' + assert arg == mock_val + + +def test_create_backup_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_backup( + metastore.CreateBackupRequest(), + parent='parent_value', + backup=metastore.Backup(name='name_value'), + backup_id='backup_id_value', + ) + +@pytest.mark.asyncio +async def test_create_backup_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_backup( + parent='parent_value', + backup=metastore.Backup(name='name_value'), + backup_id='backup_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].backup + mock_val = metastore.Backup(name='name_value') + assert arg == mock_val + arg = args[0].backup_id + mock_val = 'backup_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_backup_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_backup( + metastore.CreateBackupRequest(), + parent='parent_value', + backup=metastore.Backup(name='name_value'), + backup_id='backup_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.DeleteBackupRequest, + dict, +]) +def test_delete_backup(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.DeleteBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_backup_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_backup), + '__call__') as call: + client.delete_backup() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.DeleteBackupRequest() + +@pytest.mark.asyncio +async def test_delete_backup_async(transport: str = 'grpc_asyncio', request_type=metastore.DeleteBackupRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.DeleteBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_backup_async_from_dict(): + await test_delete_backup_async(request_type=dict) + + +def test_delete_backup_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.DeleteBackupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backup_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.DeleteBackupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backup_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_backup( + 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_backup_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_backup( + metastore.DeleteBackupRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_backup_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_backup( + 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_backup_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_backup( + metastore.DeleteBackupRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.RemoveIamPolicyRequest, + dict, +]) +def test_remove_iam_policy(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.RemoveIamPolicyResponse( + success=True, + ) + response = client.remove_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.RemoveIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.RemoveIamPolicyResponse) + assert response.success is True + + +def test_remove_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_iam_policy), + '__call__') as call: + client.remove_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.RemoveIamPolicyRequest() + +@pytest.mark.asyncio +async def test_remove_iam_policy_async(transport: str = 'grpc_asyncio', request_type=metastore.RemoveIamPolicyRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.RemoveIamPolicyResponse( + success=True, + )) + response = await client.remove_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.RemoveIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.RemoveIamPolicyResponse) + assert response.success is True + + +@pytest.mark.asyncio +async def test_remove_iam_policy_async_from_dict(): + await test_remove_iam_policy_async(request_type=dict) + + +def test_remove_iam_policy_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.RemoveIamPolicyRequest() + + request.resource = 'resource_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_iam_policy), + '__call__') as call: + call.return_value = metastore.RemoveIamPolicyResponse() + client.remove_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_iam_policy_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.RemoveIamPolicyRequest() + + request.resource = 'resource_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_iam_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.RemoveIamPolicyResponse()) + await client.remove_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + metastore.QueryMetadataRequest, + dict, +]) +def test_query_metadata(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.query_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.QueryMetadataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_query_metadata_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_metadata), + '__call__') as call: + client.query_metadata() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.QueryMetadataRequest() + +@pytest.mark.asyncio +async def test_query_metadata_async(transport: str = 'grpc_asyncio', request_type=metastore.QueryMetadataRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.query_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.QueryMetadataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_query_metadata_async_from_dict(): + await test_query_metadata_async(request_type=dict) + + +def test_query_metadata_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.QueryMetadataRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_metadata), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.query_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_query_metadata_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.QueryMetadataRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_metadata), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.query_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + metastore.MoveTableToDatabaseRequest, + dict, +]) +def test_move_table_to_database(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_table_to_database), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.move_table_to_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.MoveTableToDatabaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_move_table_to_database_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_table_to_database), + '__call__') as call: + client.move_table_to_database() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.MoveTableToDatabaseRequest() + +@pytest.mark.asyncio +async def test_move_table_to_database_async(transport: str = 'grpc_asyncio', request_type=metastore.MoveTableToDatabaseRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_table_to_database), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.move_table_to_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.MoveTableToDatabaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_move_table_to_database_async_from_dict(): + await test_move_table_to_database_async(request_type=dict) + + +def test_move_table_to_database_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.MoveTableToDatabaseRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_table_to_database), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.move_table_to_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_move_table_to_database_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.MoveTableToDatabaseRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_table_to_database), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.move_table_to_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + metastore.AlterMetadataResourceLocationRequest, + dict, +]) +def test_alter_metadata_resource_location(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.alter_metadata_resource_location), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.alter_metadata_resource_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] == metastore.AlterMetadataResourceLocationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_alter_metadata_resource_location_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.alter_metadata_resource_location), + '__call__') as call: + client.alter_metadata_resource_location() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.AlterMetadataResourceLocationRequest() + +@pytest.mark.asyncio +async def test_alter_metadata_resource_location_async(transport: str = 'grpc_asyncio', request_type=metastore.AlterMetadataResourceLocationRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.alter_metadata_resource_location), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.alter_metadata_resource_location(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.AlterMetadataResourceLocationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_alter_metadata_resource_location_async_from_dict(): + await test_alter_metadata_resource_location_async(request_type=dict) + + +def test_alter_metadata_resource_location_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.AlterMetadataResourceLocationRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.alter_metadata_resource_location), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.alter_metadata_resource_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', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_alter_metadata_resource_location_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.AlterMetadataResourceLocationRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.alter_metadata_resource_location), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.alter_metadata_resource_location(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + metastore.ListServicesRequest, + dict, +]) +def test_list_services_rest(request_type): + client = DataprocMetastoreClient( + 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 = metastore.ListServicesResponse( + 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 = metastore.ListServicesResponse.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_services(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_services_rest_required_fields(request_type=metastore.ListServicesRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_services._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_services._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.ListServicesResponse() + # 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 = metastore.ListServicesResponse.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_services(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_services_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_services._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_services_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_list_services") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_list_services") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.ListServicesRequest.pb(metastore.ListServicesRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.ListServicesResponse.to_json(metastore.ListServicesResponse()) + + request = metastore.ListServicesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.ListServicesResponse() + + client.list_services(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_services_rest_bad_request(transport: str = 'rest', request_type=metastore.ListServicesRequest): + client = DataprocMetastoreClient( + 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_services(request) + + +def test_list_services_rest_flattened(): + client = DataprocMetastoreClient( + 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 = metastore.ListServicesResponse() + + # 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 = metastore.ListServicesResponse.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_services(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=projects/*/locations/*}/services" % client.transport._host, args[1]) + + +def test_list_services_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_services( + metastore.ListServicesRequest(), + parent='parent_value', + ) + + +def test_list_services_rest_pager(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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 = ( + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + metastore.Service(), + ], + next_page_token='abc', + ), + metastore.ListServicesResponse( + services=[], + next_page_token='def', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + ], + next_page_token='ghi', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(metastore.ListServicesResponse.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_services(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore.Service) + for i in results) + + pages = list(client.list_services(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", [ + metastore.GetServiceRequest, + dict, +]) +def test_get_service_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/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 = metastore.Service( + name='name_value', + network='network_value', + endpoint_uri='endpoint_uri_value', + port=453, + state=metastore.Service.State.CREATING, + state_message='state_message_value', + artifact_gcs_uri='artifact_gcs_uri_value', + tier=metastore.Service.Tier.DEVELOPER, + uid='uid_value', + release_channel=metastore.Service.ReleaseChannel.CANARY, + database_type=metastore.Service.DatabaseType.MYSQL, + hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value'), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = metastore.Service.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_service(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.Service) + assert response.name == 'name_value' + assert response.network == 'network_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.port == 453 + assert response.state == metastore.Service.State.CREATING + assert response.state_message == 'state_message_value' + assert response.artifact_gcs_uri == 'artifact_gcs_uri_value' + assert response.tier == metastore.Service.Tier.DEVELOPER + assert response.uid == 'uid_value' + assert response.release_channel == metastore.Service.ReleaseChannel.CANARY + assert response.database_type == metastore.Service.DatabaseType.MYSQL + + +def test_get_service_rest_required_fields(request_type=metastore.GetServiceRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_service._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_service._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.Service() + # 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 = metastore.Service.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_service(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_service_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_service_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_get_service") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_get_service") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.GetServiceRequest.pb(metastore.GetServiceRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.Service.to_json(metastore.Service()) + + request = metastore.GetServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.Service() + + client.get_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_service_rest_bad_request(transport: str = 'rest', request_type=metastore.GetServiceRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/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_service(request) + + +def test_get_service_rest_flattened(): + client = DataprocMetastoreClient( + 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 = metastore.Service() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/services/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 = metastore.Service.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_service(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=projects/*/locations/*/services/*}" % client.transport._host, args[1]) + + +def test_get_service_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_service( + metastore.GetServiceRequest(), + name='name_value', + ) + + +def test_get_service_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.CreateServiceRequest, + dict, +]) +def test_create_service_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["service"] = {'hive_metastore_config': {'version': 'version_value', 'config_overrides': {}, 'kerberos_config': {'keytab': {'cloud_secret': 'cloud_secret_value'}, 'principal': 'principal_value', 'krb5_config_gcs_uri': 'krb5_config_gcs_uri_value'}, 'endpoint_protocol': 1, 'auxiliary_versions': {}}, 'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'network': 'network_value', 'endpoint_uri': 'endpoint_uri_value', 'port': 453, 'state': 1, 'state_message': 'state_message_value', 'artifact_gcs_uri': 'artifact_gcs_uri_value', 'tier': 1, 'metadata_integration': {'data_catalog_config': {'enabled': True}, 'dataplex_config': {'lake_resources': {}}}, 'maintenance_window': {'hour_of_day': {'value': 541}, 'day_of_week': 1}, 'uid': 'uid_value', 'metadata_management_activity': {'metadata_exports': [{'destination_gcs_uri': 'destination_gcs_uri_value', 'start_time': {}, 'end_time': {}, 'state': 1, 'database_dump_type': 1}], 'restores': [{'start_time': {}, 'end_time': {}, 'state': 1, 'backup': 'backup_value', 'type_': 1, 'details': 'details_value'}]}, 'release_channel': 1, 'encryption_config': {'kms_key': 'kms_key_value'}, 'network_config': {'consumers': [{'subnetwork': 'subnetwork_value', 'endpoint_uri': 'endpoint_uri_value'}]}, 'database_type': 1, 'telemetry_config': {'log_format': 1}} + request = request_type(**request_init) + + # Mock the http request call within the method and 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(name='operations/spam') + + # 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.create_service(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_service_rest_required_fields(request_type=metastore.CreateServiceRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["service_id"] = "" + 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 + assert "serviceId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "serviceId" in jsonified_request + assert jsonified_request["serviceId"] == request_init["service_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["serviceId"] = 'service_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_service._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", "service_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "serviceId" in jsonified_request + assert jsonified_request["serviceId"] == 'service_id_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_service(request) + + expected_params = [ + ( + "serviceId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_service_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "serviceId", )) & set(("parent", "serviceId", "service", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_service_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_create_service") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_create_service") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.CreateServiceRequest.pb(metastore.CreateServiceRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.CreateServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_service_rest_bad_request(transport: str = 'rest', request_type=metastore.CreateServiceRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["service"] = {'hive_metastore_config': {'version': 'version_value', 'config_overrides': {}, 'kerberos_config': {'keytab': {'cloud_secret': 'cloud_secret_value'}, 'principal': 'principal_value', 'krb5_config_gcs_uri': 'krb5_config_gcs_uri_value'}, 'endpoint_protocol': 1, 'auxiliary_versions': {}}, 'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'network': 'network_value', 'endpoint_uri': 'endpoint_uri_value', 'port': 453, 'state': 1, 'state_message': 'state_message_value', 'artifact_gcs_uri': 'artifact_gcs_uri_value', 'tier': 1, 'metadata_integration': {'data_catalog_config': {'enabled': True}, 'dataplex_config': {'lake_resources': {}}}, 'maintenance_window': {'hour_of_day': {'value': 541}, 'day_of_week': 1}, 'uid': 'uid_value', 'metadata_management_activity': {'metadata_exports': [{'destination_gcs_uri': 'destination_gcs_uri_value', 'start_time': {}, 'end_time': {}, 'state': 1, 'database_dump_type': 1}], 'restores': [{'start_time': {}, 'end_time': {}, 'state': 1, 'backup': 'backup_value', 'type_': 1, 'details': 'details_value'}]}, 'release_channel': 1, 'encryption_config': {'kms_key': 'kms_key_value'}, 'network_config': {'consumers': [{'subnetwork': 'subnetwork_value', 'endpoint_uri': 'endpoint_uri_value'}]}, 'database_type': 1, 'telemetry_config': {'log_format': 1}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_service(request) + + +def test_create_service_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # 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', + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + service_id='service_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_service(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=projects/*/locations/*}/services" % client.transport._host, args[1]) + + +def test_create_service_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_service( + metastore.CreateServiceRequest(), + parent='parent_value', + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + service_id='service_id_value', + ) + + +def test_create_service_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.UpdateServiceRequest, + dict, +]) +def test_update_service_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service': {'name': 'projects/sample1/locations/sample2/services/sample3'}} + request_init["service"] = {'hive_metastore_config': {'version': 'version_value', 'config_overrides': {}, 'kerberos_config': {'keytab': {'cloud_secret': 'cloud_secret_value'}, 'principal': 'principal_value', 'krb5_config_gcs_uri': 'krb5_config_gcs_uri_value'}, 'endpoint_protocol': 1, 'auxiliary_versions': {}}, 'name': 'projects/sample1/locations/sample2/services/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'network': 'network_value', 'endpoint_uri': 'endpoint_uri_value', 'port': 453, 'state': 1, 'state_message': 'state_message_value', 'artifact_gcs_uri': 'artifact_gcs_uri_value', 'tier': 1, 'metadata_integration': {'data_catalog_config': {'enabled': True}, 'dataplex_config': {'lake_resources': {}}}, 'maintenance_window': {'hour_of_day': {'value': 541}, 'day_of_week': 1}, 'uid': 'uid_value', 'metadata_management_activity': {'metadata_exports': [{'destination_gcs_uri': 'destination_gcs_uri_value', 'start_time': {}, 'end_time': {}, 'state': 1, 'database_dump_type': 1}], 'restores': [{'start_time': {}, 'end_time': {}, 'state': 1, 'backup': 'backup_value', 'type_': 1, 'details': 'details_value'}]}, 'release_channel': 1, 'encryption_config': {'kms_key': 'kms_key_value'}, 'network_config': {'consumers': [{'subnetwork': 'subnetwork_value', 'endpoint_uri': 'endpoint_uri_value'}]}, 'database_type': 1, 'telemetry_config': {'log_format': 1}} + request = request_type(**request_init) + + # Mock the http request call within the method and 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(name='operations/spam') + + # 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.update_service(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_service_rest_required_fields(request_type=metastore.UpdateServiceRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_service._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_service._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_service(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_service_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "service", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_service_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_update_service") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_update_service") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.UpdateServiceRequest.pb(metastore.UpdateServiceRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.UpdateServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_service_rest_bad_request(transport: str = 'rest', request_type=metastore.UpdateServiceRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service': {'name': 'projects/sample1/locations/sample2/services/sample3'}} + request_init["service"] = {'hive_metastore_config': {'version': 'version_value', 'config_overrides': {}, 'kerberos_config': {'keytab': {'cloud_secret': 'cloud_secret_value'}, 'principal': 'principal_value', 'krb5_config_gcs_uri': 'krb5_config_gcs_uri_value'}, 'endpoint_protocol': 1, 'auxiliary_versions': {}}, 'name': 'projects/sample1/locations/sample2/services/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'network': 'network_value', 'endpoint_uri': 'endpoint_uri_value', 'port': 453, 'state': 1, 'state_message': 'state_message_value', 'artifact_gcs_uri': 'artifact_gcs_uri_value', 'tier': 1, 'metadata_integration': {'data_catalog_config': {'enabled': True}, 'dataplex_config': {'lake_resources': {}}}, 'maintenance_window': {'hour_of_day': {'value': 541}, 'day_of_week': 1}, 'uid': 'uid_value', 'metadata_management_activity': {'metadata_exports': [{'destination_gcs_uri': 'destination_gcs_uri_value', 'start_time': {}, 'end_time': {}, 'state': 1, 'database_dump_type': 1}], 'restores': [{'start_time': {}, 'end_time': {}, 'state': 1, 'backup': 'backup_value', 'type_': 1, 'details': 'details_value'}]}, 'release_channel': 1, 'encryption_config': {'kms_key': 'kms_key_value'}, 'network_config': {'consumers': [{'subnetwork': 'subnetwork_value', 'endpoint_uri': 'endpoint_uri_value'}]}, 'database_type': 1, 'telemetry_config': {'log_format': 1}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_service(request) + + +def test_update_service_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'service': {'name': 'projects/sample1/locations/sample2/services/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_service(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{service.name=projects/*/locations/*/services/*}" % client.transport._host, args[1]) + + +def test_update_service_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_service( + metastore.UpdateServiceRequest(), + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_service_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.DeleteServiceRequest, + dict, +]) +def test_delete_service_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/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(name='operations/spam') + + # 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.delete_service(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_service_rest_required_fields(request_type=metastore.DeleteServiceRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_service._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_service._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 "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # 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 = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_service(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_service_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_service_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_delete_service") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_delete_service") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.DeleteServiceRequest.pb(metastore.DeleteServiceRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.DeleteServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_service_rest_bad_request(transport: str = 'rest', request_type=metastore.DeleteServiceRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/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_service(request) + + +def test_delete_service_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/services/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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_service(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=projects/*/locations/*/services/*}" % client.transport._host, args[1]) + + +def test_delete_service_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_service( + metastore.DeleteServiceRequest(), + name='name_value', + ) + + +def test_delete_service_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ListMetadataImportsRequest, + dict, +]) +def test_list_metadata_imports_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/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 = metastore.ListMetadataImportsResponse( + 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 = metastore.ListMetadataImportsResponse.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_metadata_imports(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMetadataImportsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_metadata_imports_rest_required_fields(request_type=metastore.ListMetadataImportsRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_metadata_imports._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_metadata_imports._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.ListMetadataImportsResponse() + # 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 = metastore.ListMetadataImportsResponse.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_metadata_imports(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_metadata_imports_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_metadata_imports._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_metadata_imports_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_list_metadata_imports") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_list_metadata_imports") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.ListMetadataImportsRequest.pb(metastore.ListMetadataImportsRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.ListMetadataImportsResponse.to_json(metastore.ListMetadataImportsResponse()) + + request = metastore.ListMetadataImportsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.ListMetadataImportsResponse() + + client.list_metadata_imports(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_metadata_imports_rest_bad_request(transport: str = 'rest', request_type=metastore.ListMetadataImportsRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/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_metadata_imports(request) + + +def test_list_metadata_imports_rest_flattened(): + client = DataprocMetastoreClient( + 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 = metastore.ListMetadataImportsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/services/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 = metastore.ListMetadataImportsResponse.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_metadata_imports(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=projects/*/locations/*/services/*}/metadataImports" % client.transport._host, args[1]) + + +def test_list_metadata_imports_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_metadata_imports( + metastore.ListMetadataImportsRequest(), + parent='parent_value', + ) + + +def test_list_metadata_imports_rest_pager(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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 = ( + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + next_page_token='abc', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[], + next_page_token='def', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + ], + next_page_token='ghi', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(metastore.ListMetadataImportsResponse.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/services/sample3'} + + pager = client.list_metadata_imports(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore.MetadataImport) + for i in results) + + pages = list(client.list_metadata_imports(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", [ + metastore.GetMetadataImportRequest, + dict, +]) +def test_get_metadata_import_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/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 = metastore.MetadataImport( + name='name_value', + description='description_value', + state=metastore.MetadataImport.State.RUNNING, + database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = metastore.MetadataImport.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_metadata_import(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.MetadataImport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == metastore.MetadataImport.State.RUNNING + + +def test_get_metadata_import_rest_required_fields(request_type=metastore.GetMetadataImportRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_metadata_import._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_metadata_import._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.MetadataImport() + # 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 = metastore.MetadataImport.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_metadata_import(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_metadata_import_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_metadata_import._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_metadata_import_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_get_metadata_import") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_get_metadata_import") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.GetMetadataImportRequest.pb(metastore.GetMetadataImportRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.MetadataImport.to_json(metastore.MetadataImport()) + + request = metastore.GetMetadataImportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.MetadataImport() + + client.get_metadata_import(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_metadata_import_rest_bad_request(transport: str = 'rest', request_type=metastore.GetMetadataImportRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/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_metadata_import(request) + + +def test_get_metadata_import_rest_flattened(): + client = DataprocMetastoreClient( + 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 = metastore.MetadataImport() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/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 = metastore.MetadataImport.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_metadata_import(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=projects/*/locations/*/services/*/metadataImports/*}" % client.transport._host, args[1]) + + +def test_get_metadata_import_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_metadata_import( + metastore.GetMetadataImportRequest(), + name='name_value', + ) + + +def test_get_metadata_import_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.CreateMetadataImportRequest, + dict, +]) +def test_create_metadata_import_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/sample3'} + request_init["metadata_import"] = {'database_dump': {'database_type': 1, 'gcs_uri': 'gcs_uri_value', 'source_database': 'source_database_value', 'type_': 1}, 'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'end_time': {}, 'state': 1} + request = request_type(**request_init) + + # Mock the http request call within the method and 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(name='operations/spam') + + # 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.create_metadata_import(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_metadata_import_rest_required_fields(request_type=metastore.CreateMetadataImportRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["metadata_import_id"] = "" + 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 + assert "metadataImportId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_metadata_import._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "metadataImportId" in jsonified_request + assert jsonified_request["metadataImportId"] == request_init["metadata_import_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["metadataImportId"] = 'metadata_import_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_metadata_import._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("metadata_import_id", "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' + assert "metadataImportId" in jsonified_request + assert jsonified_request["metadataImportId"] == 'metadata_import_id_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_metadata_import(request) + + expected_params = [ + ( + "metadataImportId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_metadata_import_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_metadata_import._get_unset_required_fields({}) + assert set(unset_fields) == (set(("metadataImportId", "requestId", )) & set(("parent", "metadataImportId", "metadataImport", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_metadata_import_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_create_metadata_import") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_create_metadata_import") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.CreateMetadataImportRequest.pb(metastore.CreateMetadataImportRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.CreateMetadataImportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_metadata_import(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_metadata_import_rest_bad_request(transport: str = 'rest', request_type=metastore.CreateMetadataImportRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/sample3'} + request_init["metadata_import"] = {'database_dump': {'database_type': 1, 'gcs_uri': 'gcs_uri_value', 'source_database': 'source_database_value', 'type_': 1}, 'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'end_time': {}, 'state': 1} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_metadata_import(request) + + +def test_create_metadata_import_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/services/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + metadata_import_id='metadata_import_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_metadata_import(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=projects/*/locations/*/services/*}/metadataImports" % client.transport._host, args[1]) + + +def test_create_metadata_import_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_metadata_import( + metastore.CreateMetadataImportRequest(), + parent='parent_value', + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + metadata_import_id='metadata_import_id_value', + ) + + +def test_create_metadata_import_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.UpdateMetadataImportRequest, + dict, +]) +def test_update_metadata_import_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'metadata_import': {'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/sample4'}} + request_init["metadata_import"] = {'database_dump': {'database_type': 1, 'gcs_uri': 'gcs_uri_value', 'source_database': 'source_database_value', 'type_': 1}, 'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/sample4', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'end_time': {}, 'state': 1} + request = request_type(**request_init) + + # Mock the http request call within the method and 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(name='operations/spam') + + # 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.update_metadata_import(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_metadata_import_rest_required_fields(request_type=metastore.UpdateMetadataImportRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_metadata_import._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_metadata_import._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_metadata_import(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_metadata_import_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_metadata_import._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "metadataImport", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_metadata_import_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_update_metadata_import") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_update_metadata_import") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.UpdateMetadataImportRequest.pb(metastore.UpdateMetadataImportRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.UpdateMetadataImportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_metadata_import(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_metadata_import_rest_bad_request(transport: str = 'rest', request_type=metastore.UpdateMetadataImportRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'metadata_import': {'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/sample4'}} + request_init["metadata_import"] = {'database_dump': {'database_type': 1, 'gcs_uri': 'gcs_uri_value', 'source_database': 'source_database_value', 'type_': 1}, 'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/sample4', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'end_time': {}, 'state': 1} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_metadata_import(request) + + +def test_update_metadata_import_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'metadata_import': {'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + 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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_metadata_import(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{metadata_import.name=projects/*/locations/*/services/*/metadataImports/*}" % client.transport._host, args[1]) + + +def test_update_metadata_import_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_metadata_import( + metastore.UpdateMetadataImportRequest(), + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_metadata_import_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ExportMetadataRequest, + dict, +]) +def test_export_metadata_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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(name='operations/spam') + + # 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.export_metadata(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_export_metadata_rest_required_fields(request_type=metastore.ExportMetadataRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["service"] = "" + 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()).export_metadata._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["service"] = 'service_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_metadata._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "service" in jsonified_request + assert jsonified_request["service"] == 'service_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.export_metadata(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_export_metadata_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.export_metadata._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("service", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_metadata_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_export_metadata") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_export_metadata") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.ExportMetadataRequest.pb(metastore.ExportMetadataRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.ExportMetadataRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.export_metadata(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_export_metadata_rest_bad_request(transport: str = 'rest', request_type=metastore.ExportMetadataRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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.export_metadata(request) + + +def test_export_metadata_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.RestoreServiceRequest, + dict, +]) +def test_restore_service_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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(name='operations/spam') + + # 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.restore_service(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_restore_service_rest_required_fields(request_type=metastore.RestoreServiceRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["service"] = "" + request_init["backup"] = "" + 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()).restore_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["service"] = 'service_value' + jsonified_request["backup"] = 'backup_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).restore_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "service" in jsonified_request + assert jsonified_request["service"] == 'service_value' + assert "backup" in jsonified_request + assert jsonified_request["backup"] == 'backup_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.restore_service(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_restore_service_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.restore_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("service", "backup", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_restore_service_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_restore_service") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_restore_service") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.RestoreServiceRequest.pb(metastore.RestoreServiceRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.RestoreServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.restore_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_restore_service_rest_bad_request(transport: str = 'rest', request_type=metastore.RestoreServiceRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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.restore_service(request) + + +def test_restore_service_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'service': 'projects/sample1/locations/sample2/services/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + service='service_value', + backup='backup_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.restore_service(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{service=projects/*/locations/*/services/*}:restore" % client.transport._host, args[1]) + + +def test_restore_service_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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.restore_service( + metastore.RestoreServiceRequest(), + service='service_value', + backup='backup_value', + ) + + +def test_restore_service_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ListBackupsRequest, + dict, +]) +def test_list_backups_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/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 = metastore.ListBackupsResponse( + 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 = metastore.ListBackupsResponse.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_backups(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_backups_rest_required_fields(request_type=metastore.ListBackupsRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_backups._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_backups._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.ListBackupsResponse() + # 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 = metastore.ListBackupsResponse.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_backups(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_backups_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_backups._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_backups_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_list_backups") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_list_backups") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.ListBackupsRequest.pb(metastore.ListBackupsRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.ListBackupsResponse.to_json(metastore.ListBackupsResponse()) + + request = metastore.ListBackupsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.ListBackupsResponse() + + client.list_backups(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_backups_rest_bad_request(transport: str = 'rest', request_type=metastore.ListBackupsRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/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_backups(request) + + +def test_list_backups_rest_flattened(): + client = DataprocMetastoreClient( + 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 = metastore.ListBackupsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/services/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 = metastore.ListBackupsResponse.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_backups(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=projects/*/locations/*/services/*}/backups" % client.transport._host, args[1]) + + +def test_list_backups_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_backups( + metastore.ListBackupsRequest(), + parent='parent_value', + ) + + +def test_list_backups_rest_pager(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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 = ( + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + metastore.Backup(), + ], + next_page_token='abc', + ), + metastore.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + ], + next_page_token='ghi', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(metastore.ListBackupsResponse.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/services/sample3'} + + pager = client.list_backups(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore.Backup) + for i in results) + + pages = list(client.list_backups(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", [ + metastore.GetBackupRequest, + dict, +]) +def test_get_backup_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/sample3/backups/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 = metastore.Backup( + name='name_value', + state=metastore.Backup.State.CREATING, + description='description_value', + restoring_services=['restoring_services_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = metastore.Backup.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_backup(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.Backup) + assert response.name == 'name_value' + assert response.state == metastore.Backup.State.CREATING + assert response.description == 'description_value' + assert response.restoring_services == ['restoring_services_value'] + + +def test_get_backup_rest_required_fields(request_type=metastore.GetBackupRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_backup._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_backup._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.Backup() + # 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 = metastore.Backup.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_backup(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_backup_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_backup_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_get_backup") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_get_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.GetBackupRequest.pb(metastore.GetBackupRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.Backup.to_json(metastore.Backup()) + + request = metastore.GetBackupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.Backup() + + client.get_backup(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_backup_rest_bad_request(transport: str = 'rest', request_type=metastore.GetBackupRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/sample3/backups/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_backup(request) + + +def test_get_backup_rest_flattened(): + client = DataprocMetastoreClient( + 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 = metastore.Backup() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/services/sample3/backups/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 = metastore.Backup.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_backup(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=projects/*/locations/*/services/*/backups/*}" % client.transport._host, args[1]) + + +def test_get_backup_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_backup( + metastore.GetBackupRequest(), + name='name_value', + ) + + +def test_get_backup_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.CreateBackupRequest, + dict, +]) +def test_create_backup_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/sample3'} + request_init["backup"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}, 'state': 1, 'service_revision': {'hive_metastore_config': {'version': 'version_value', 'config_overrides': {}, 'kerberos_config': {'keytab': {'cloud_secret': 'cloud_secret_value'}, 'principal': 'principal_value', 'krb5_config_gcs_uri': 'krb5_config_gcs_uri_value'}, 'endpoint_protocol': 1, 'auxiliary_versions': {}}, 'name': 'name_value', 'create_time': {}, 'update_time': {}, 'labels': {}, 'network': 'network_value', 'endpoint_uri': 'endpoint_uri_value', 'port': 453, 'state': 1, 'state_message': 'state_message_value', 'artifact_gcs_uri': 'artifact_gcs_uri_value', 'tier': 1, 'metadata_integration': {'data_catalog_config': {'enabled': True}, 'dataplex_config': {'lake_resources': {}}}, 'maintenance_window': {'hour_of_day': {'value': 541}, 'day_of_week': 1}, 'uid': 'uid_value', 'metadata_management_activity': {'metadata_exports': [{'destination_gcs_uri': 'destination_gcs_uri_value', 'start_time': {}, 'end_time': {}, 'state': 1, 'database_dump_type': 1}], 'restores': [{'start_time': {}, 'end_time': {}, 'state': 1, 'backup': 'backup_value', 'type_': 1, 'details': 'details_value'}]}, 'release_channel': 1, 'encryption_config': {'kms_key': 'kms_key_value'}, 'network_config': {'consumers': [{'subnetwork': 'subnetwork_value', 'endpoint_uri': 'endpoint_uri_value'}]}, 'database_type': 1, 'telemetry_config': {'log_format': 1}}, 'description': 'description_value', 'restoring_services': ['restoring_services_value1', 'restoring_services_value2']} + request = request_type(**request_init) + + # Mock the http request call within the method and 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(name='operations/spam') + + # 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.create_backup(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_backup_rest_required_fields(request_type=metastore.CreateBackupRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["backup_id"] = "" + 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 + assert "backupId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_backup._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "backupId" in jsonified_request + assert jsonified_request["backupId"] == request_init["backup_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["backupId"] = 'backup_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_backup._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("backup_id", "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' + assert "backupId" in jsonified_request + assert jsonified_request["backupId"] == 'backup_id_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_backup(request) + + expected_params = [ + ( + "backupId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_backup_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(("backupId", "requestId", )) & set(("parent", "backupId", "backup", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_backup_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_create_backup") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_create_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.CreateBackupRequest.pb(metastore.CreateBackupRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.CreateBackupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_backup(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_backup_rest_bad_request(transport: str = 'rest', request_type=metastore.CreateBackupRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/sample3'} + request_init["backup"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}, 'state': 1, 'service_revision': {'hive_metastore_config': {'version': 'version_value', 'config_overrides': {}, 'kerberos_config': {'keytab': {'cloud_secret': 'cloud_secret_value'}, 'principal': 'principal_value', 'krb5_config_gcs_uri': 'krb5_config_gcs_uri_value'}, 'endpoint_protocol': 1, 'auxiliary_versions': {}}, 'name': 'name_value', 'create_time': {}, 'update_time': {}, 'labels': {}, 'network': 'network_value', 'endpoint_uri': 'endpoint_uri_value', 'port': 453, 'state': 1, 'state_message': 'state_message_value', 'artifact_gcs_uri': 'artifact_gcs_uri_value', 'tier': 1, 'metadata_integration': {'data_catalog_config': {'enabled': True}, 'dataplex_config': {'lake_resources': {}}}, 'maintenance_window': {'hour_of_day': {'value': 541}, 'day_of_week': 1}, 'uid': 'uid_value', 'metadata_management_activity': {'metadata_exports': [{'destination_gcs_uri': 'destination_gcs_uri_value', 'start_time': {}, 'end_time': {}, 'state': 1, 'database_dump_type': 1}], 'restores': [{'start_time': {}, 'end_time': {}, 'state': 1, 'backup': 'backup_value', 'type_': 1, 'details': 'details_value'}]}, 'release_channel': 1, 'encryption_config': {'kms_key': 'kms_key_value'}, 'network_config': {'consumers': [{'subnetwork': 'subnetwork_value', 'endpoint_uri': 'endpoint_uri_value'}]}, 'database_type': 1, 'telemetry_config': {'log_format': 1}}, 'description': 'description_value', 'restoring_services': ['restoring_services_value1', 'restoring_services_value2']} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_backup(request) + + +def test_create_backup_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/services/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + backup=metastore.Backup(name='name_value'), + backup_id='backup_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_backup(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=projects/*/locations/*/services/*}/backups" % client.transport._host, args[1]) + + +def test_create_backup_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_backup( + metastore.CreateBackupRequest(), + parent='parent_value', + backup=metastore.Backup(name='name_value'), + backup_id='backup_id_value', + ) + + +def test_create_backup_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.DeleteBackupRequest, + dict, +]) +def test_delete_backup_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/sample3/backups/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 = operations_pb2.Operation(name='operations/spam') + + # 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.delete_backup(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_backup_rest_required_fields(request_type=metastore.DeleteBackupRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_backup._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_backup._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 "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # 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 = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_backup(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_backup_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_backup_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_delete_backup") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_delete_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.DeleteBackupRequest.pb(metastore.DeleteBackupRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.DeleteBackupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_backup(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_backup_rest_bad_request(transport: str = 'rest', request_type=metastore.DeleteBackupRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/sample3/backups/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.delete_backup(request) + + +def test_delete_backup_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/services/sample3/backups/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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_backup(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=projects/*/locations/*/services/*/backups/*}" % client.transport._host, args[1]) + + +def test_delete_backup_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_backup( + metastore.DeleteBackupRequest(), + name='name_value', + ) + + +def test_delete_backup_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.RemoveIamPolicyRequest, + dict, +]) +def test_remove_iam_policy_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'projects/sample1/locations/sample2/services/sample3/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 = metastore.RemoveIamPolicyResponse( + success=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = metastore.RemoveIamPolicyResponse.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.remove_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.RemoveIamPolicyResponse) + assert response.success is True + + +def test_remove_iam_policy_rest_required_fields(request_type=metastore.RemoveIamPolicyRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["resource"] = "" + 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()).remove_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.RemoveIamPolicyResponse() + # 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 = metastore.RemoveIamPolicyResponse.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.remove_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_remove_iam_policy_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.remove_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_remove_iam_policy_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_remove_iam_policy") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_remove_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.RemoveIamPolicyRequest.pb(metastore.RemoveIamPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.RemoveIamPolicyResponse.to_json(metastore.RemoveIamPolicyResponse()) + + request = metastore.RemoveIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.RemoveIamPolicyResponse() + + client.remove_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_remove_iam_policy_rest_bad_request(transport: str = 'rest', request_type=metastore.RemoveIamPolicyRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'projects/sample1/locations/sample2/services/sample3/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.remove_iam_policy(request) + + +def test_remove_iam_policy_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.QueryMetadataRequest, + dict, +]) +def test_query_metadata_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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(name='operations/spam') + + # 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.query_metadata(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_query_metadata_rest_required_fields(request_type=metastore.QueryMetadataRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["service"] = "" + request_init["query"] = "" + 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()).query_metadata._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["service"] = 'service_value' + jsonified_request["query"] = 'query_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).query_metadata._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "service" in jsonified_request + assert jsonified_request["service"] == 'service_value' + assert "query" in jsonified_request + assert jsonified_request["query"] == 'query_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.query_metadata(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_query_metadata_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.query_metadata._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("service", "query", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_query_metadata_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_query_metadata") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_query_metadata") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.QueryMetadataRequest.pb(metastore.QueryMetadataRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.QueryMetadataRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.query_metadata(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_query_metadata_rest_bad_request(transport: str = 'rest', request_type=metastore.QueryMetadataRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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.query_metadata(request) + + +def test_query_metadata_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.MoveTableToDatabaseRequest, + dict, +]) +def test_move_table_to_database_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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(name='operations/spam') + + # 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.move_table_to_database(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_move_table_to_database_rest_required_fields(request_type=metastore.MoveTableToDatabaseRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["service"] = "" + request_init["table_name"] = "" + request_init["db_name"] = "" + request_init["destination_db_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()).move_table_to_database._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["service"] = 'service_value' + jsonified_request["tableName"] = 'table_name_value' + jsonified_request["dbName"] = 'db_name_value' + jsonified_request["destinationDbName"] = 'destination_db_name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).move_table_to_database._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "service" in jsonified_request + assert jsonified_request["service"] == 'service_value' + assert "tableName" in jsonified_request + assert jsonified_request["tableName"] == 'table_name_value' + assert "dbName" in jsonified_request + assert jsonified_request["dbName"] == 'db_name_value' + assert "destinationDbName" in jsonified_request + assert jsonified_request["destinationDbName"] == 'destination_db_name_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.move_table_to_database(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_move_table_to_database_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.move_table_to_database._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("service", "tableName", "dbName", "destinationDbName", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_move_table_to_database_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_move_table_to_database") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_move_table_to_database") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.MoveTableToDatabaseRequest.pb(metastore.MoveTableToDatabaseRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.MoveTableToDatabaseRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.move_table_to_database(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_move_table_to_database_rest_bad_request(transport: str = 'rest', request_type=metastore.MoveTableToDatabaseRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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.move_table_to_database(request) + + +def test_move_table_to_database_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.AlterMetadataResourceLocationRequest, + dict, +]) +def test_alter_metadata_resource_location_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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(name='operations/spam') + + # 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.alter_metadata_resource_location(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_alter_metadata_resource_location_rest_required_fields(request_type=metastore.AlterMetadataResourceLocationRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["service"] = "" + request_init["resource_name"] = "" + request_init["location_uri"] = "" + 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()).alter_metadata_resource_location._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["service"] = 'service_value' + jsonified_request["resourceName"] = 'resource_name_value' + jsonified_request["locationUri"] = 'location_uri_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).alter_metadata_resource_location._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "service" in jsonified_request + assert jsonified_request["service"] == 'service_value' + assert "resourceName" in jsonified_request + assert jsonified_request["resourceName"] == 'resource_name_value' + assert "locationUri" in jsonified_request + assert jsonified_request["locationUri"] == 'location_uri_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.alter_metadata_resource_location(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_alter_metadata_resource_location_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.alter_metadata_resource_location._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("service", "resourceName", "locationUri", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_alter_metadata_resource_location_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_alter_metadata_resource_location") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_alter_metadata_resource_location") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.AlterMetadataResourceLocationRequest.pb(metastore.AlterMetadataResourceLocationRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.AlterMetadataResourceLocationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.alter_metadata_resource_location(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_alter_metadata_resource_location_rest_bad_request(transport: str = 'rest', request_type=metastore.AlterMetadataResourceLocationRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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.alter_metadata_resource_location(request) + + +def test_alter_metadata_resource_location_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DataprocMetastoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DataprocMetastoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataprocMetastoreClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DataprocMetastoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DataprocMetastoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataprocMetastoreClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataprocMetastoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DataprocMetastoreClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataprocMetastoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DataprocMetastoreGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DataprocMetastoreGrpcTransport, + transports.DataprocMetastoreGrpcAsyncIOTransport, + transports.DataprocMetastoreRestTransport, +]) +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 = DataprocMetastoreClient.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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DataprocMetastoreGrpcTransport, + ) + +def test_dataproc_metastore_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DataprocMetastoreTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_dataproc_metastore_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.metastore_v1alpha.services.dataproc_metastore.transports.DataprocMetastoreTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DataprocMetastoreTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_services', + 'get_service', + 'create_service', + 'update_service', + 'delete_service', + 'list_metadata_imports', + 'get_metadata_import', + 'create_metadata_import', + 'update_metadata_import', + 'export_metadata', + 'restore_service', + 'list_backups', + 'get_backup', + 'create_backup', + 'delete_backup', + 'remove_iam_policy', + 'query_metadata', + 'move_table_to_database', + 'alter_metadata_resource_location', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_dataproc_metastore_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.metastore_v1alpha.services.dataproc_metastore.transports.DataprocMetastoreTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataprocMetastoreTransport( + 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_dataproc_metastore_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.metastore_v1alpha.services.dataproc_metastore.transports.DataprocMetastoreTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataprocMetastoreTransport() + adc.assert_called_once() + + +def test_dataproc_metastore_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) + DataprocMetastoreClient() + 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.DataprocMetastoreGrpcTransport, + transports.DataprocMetastoreGrpcAsyncIOTransport, + ], +) +def test_dataproc_metastore_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.DataprocMetastoreGrpcTransport, + transports.DataprocMetastoreGrpcAsyncIOTransport, + transports.DataprocMetastoreRestTransport, + ], +) +def test_dataproc_metastore_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.DataprocMetastoreGrpcTransport, grpc_helpers), + (transports.DataprocMetastoreGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_dataproc_metastore_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( + "metastore.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="metastore.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DataprocMetastoreGrpcTransport, transports.DataprocMetastoreGrpcAsyncIOTransport]) +def test_dataproc_metastore_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_dataproc_metastore_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.DataprocMetastoreRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_dataproc_metastore_rest_lro_client(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_dataproc_metastore_host_no_port(transport_name): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='metastore.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'metastore.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://metastore.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_dataproc_metastore_host_with_port(transport_name): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='metastore.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'metastore.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://metastore.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_dataproc_metastore_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DataprocMetastoreClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DataprocMetastoreClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_services._session + session2 = client2.transport.list_services._session + assert session1 != session2 + session1 = client1.transport.get_service._session + session2 = client2.transport.get_service._session + assert session1 != session2 + session1 = client1.transport.create_service._session + session2 = client2.transport.create_service._session + assert session1 != session2 + session1 = client1.transport.update_service._session + session2 = client2.transport.update_service._session + assert session1 != session2 + session1 = client1.transport.delete_service._session + session2 = client2.transport.delete_service._session + assert session1 != session2 + session1 = client1.transport.list_metadata_imports._session + session2 = client2.transport.list_metadata_imports._session + assert session1 != session2 + session1 = client1.transport.get_metadata_import._session + session2 = client2.transport.get_metadata_import._session + assert session1 != session2 + session1 = client1.transport.create_metadata_import._session + session2 = client2.transport.create_metadata_import._session + assert session1 != session2 + session1 = client1.transport.update_metadata_import._session + session2 = client2.transport.update_metadata_import._session + assert session1 != session2 + session1 = client1.transport.export_metadata._session + session2 = client2.transport.export_metadata._session + assert session1 != session2 + session1 = client1.transport.restore_service._session + session2 = client2.transport.restore_service._session + assert session1 != session2 + session1 = client1.transport.list_backups._session + session2 = client2.transport.list_backups._session + assert session1 != session2 + session1 = client1.transport.get_backup._session + session2 = client2.transport.get_backup._session + assert session1 != session2 + session1 = client1.transport.create_backup._session + session2 = client2.transport.create_backup._session + assert session1 != session2 + session1 = client1.transport.delete_backup._session + session2 = client2.transport.delete_backup._session + assert session1 != session2 + session1 = client1.transport.remove_iam_policy._session + session2 = client2.transport.remove_iam_policy._session + assert session1 != session2 + session1 = client1.transport.query_metadata._session + session2 = client2.transport.query_metadata._session + assert session1 != session2 + session1 = client1.transport.move_table_to_database._session + session2 = client2.transport.move_table_to_database._session + assert session1 != session2 + session1 = client1.transport.alter_metadata_resource_location._session + session2 = client2.transport.alter_metadata_resource_location._session + assert session1 != session2 +def test_dataproc_metastore_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataprocMetastoreGrpcTransport( + 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_dataproc_metastore_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataprocMetastoreGrpcAsyncIOTransport( + 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.DataprocMetastoreGrpcTransport, transports.DataprocMetastoreGrpcAsyncIOTransport]) +def test_dataproc_metastore_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.DataprocMetastoreGrpcTransport, transports.DataprocMetastoreGrpcAsyncIOTransport]) +def test_dataproc_metastore_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_dataproc_metastore_grpc_lro_client(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_dataproc_metastore_grpc_lro_async_client(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_backup_path(): + project = "squid" + location = "clam" + service = "whelk" + backup = "octopus" + expected = "projects/{project}/locations/{location}/services/{service}/backups/{backup}".format(project=project, location=location, service=service, backup=backup, ) + actual = DataprocMetastoreClient.backup_path(project, location, service, backup) + assert expected == actual + + +def test_parse_backup_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "service": "cuttlefish", + "backup": "mussel", + } + path = DataprocMetastoreClient.backup_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_backup_path(path) + assert expected == actual + +def test_lake_path(): + project = "winkle" + location = "nautilus" + lake = "scallop" + expected = "projects/{project}/locations/{location}/lakes/{lake}".format(project=project, location=location, lake=lake, ) + actual = DataprocMetastoreClient.lake_path(project, location, lake) + assert expected == actual + + +def test_parse_lake_path(): + expected = { + "project": "abalone", + "location": "squid", + "lake": "clam", + } + path = DataprocMetastoreClient.lake_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_lake_path(path) + assert expected == actual + +def test_metadata_import_path(): + project = "whelk" + location = "octopus" + service = "oyster" + metadata_import = "nudibranch" + expected = "projects/{project}/locations/{location}/services/{service}/metadataImports/{metadata_import}".format(project=project, location=location, service=service, metadata_import=metadata_import, ) + actual = DataprocMetastoreClient.metadata_import_path(project, location, service, metadata_import) + assert expected == actual + + +def test_parse_metadata_import_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "service": "winkle", + "metadata_import": "nautilus", + } + path = DataprocMetastoreClient.metadata_import_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_metadata_import_path(path) + assert expected == actual + +def test_network_path(): + project = "scallop" + network = "abalone" + expected = "projects/{project}/global/networks/{network}".format(project=project, network=network, ) + actual = DataprocMetastoreClient.network_path(project, network) + assert expected == actual + + +def test_parse_network_path(): + expected = { + "project": "squid", + "network": "clam", + } + path = DataprocMetastoreClient.network_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_network_path(path) + assert expected == actual + +def test_service_path(): + project = "whelk" + location = "octopus" + service = "oyster" + expected = "projects/{project}/locations/{location}/services/{service}".format(project=project, location=location, service=service, ) + actual = DataprocMetastoreClient.service_path(project, location, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "service": "mussel", + } + path = DataprocMetastoreClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_service_path(path) + assert expected == actual + +def test_subnetwork_path(): + project = "winkle" + region = "nautilus" + subnetwork = "scallop" + expected = "projects/{project}/regions/{region}/subnetworks/{subnetwork}".format(project=project, region=region, subnetwork=subnetwork, ) + actual = DataprocMetastoreClient.subnetwork_path(project, region, subnetwork) + assert expected == actual + + +def test_parse_subnetwork_path(): + expected = { + "project": "abalone", + "region": "squid", + "subnetwork": "clam", + } + path = DataprocMetastoreClient.subnetwork_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_subnetwork_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DataprocMetastoreClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = DataprocMetastoreClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = DataprocMetastoreClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = DataprocMetastoreClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DataprocMetastoreClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = DataprocMetastoreClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = DataprocMetastoreClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = DataprocMetastoreClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.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 = DataprocMetastoreClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = DataprocMetastoreClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.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.DataprocMetastoreTransport, '_prep_wrapped_messages') as prep: + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DataprocMetastoreTransport, '_prep_wrapped_messages') as prep: + transport_class = DataprocMetastoreClient.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 = DataprocMetastoreAsyncClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/services/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_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/services/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 = policy_pb2.Policy() + + # 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_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/services/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.set_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/services/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 = policy_pb2.Policy() + + # 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.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/services/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.test_iam_permissions(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/services/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 = iam_policy_pb2.TestIamPermissionsResponse() + + # 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.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreAsyncClient( + 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_get_operation(transport: str = "grpc"): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreAsyncClient( + 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreAsyncClient( + 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreAsyncClient( + 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreAsyncClient( + 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_set_iam_policy(transport: str = "grpc"): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the 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, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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", [ + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v1alpha/tests/unit/gapic/metastore_v1alpha/test_dataproc_metastore_federation.py b/owl-bot-staging/v1alpha/tests/unit/gapic/metastore_v1alpha/test_dataproc_metastore_federation.py new file mode 100644 index 0000000..47f91ac --- /dev/null +++ b/owl-bot-staging/v1alpha/tests/unit/gapic/metastore_v1alpha/test_dataproc_metastore_federation.py @@ -0,0 +1,5435 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.metastore_v1alpha.services.dataproc_metastore_federation import DataprocMetastoreFederationAsyncClient +from google.cloud.metastore_v1alpha.services.dataproc_metastore_federation import DataprocMetastoreFederationClient +from google.cloud.metastore_v1alpha.services.dataproc_metastore_federation import pagers +from google.cloud.metastore_v1alpha.services.dataproc_metastore_federation import transports +from google.cloud.metastore_v1alpha.types import metastore +from google.cloud.metastore_v1alpha.types import metastore_federation +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DataprocMetastoreFederationClient._get_default_mtls_endpoint(None) is None + assert DataprocMetastoreFederationClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DataprocMetastoreFederationClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DataprocMetastoreFederationClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DataprocMetastoreFederationClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DataprocMetastoreFederationClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DataprocMetastoreFederationClient, "grpc"), + (DataprocMetastoreFederationAsyncClient, "grpc_asyncio"), + (DataprocMetastoreFederationClient, "rest"), +]) +def test_dataproc_metastore_federation_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 == ( + 'metastore.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://metastore.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DataprocMetastoreFederationGrpcTransport, "grpc"), + (transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DataprocMetastoreFederationRestTransport, "rest"), +]) +def test_dataproc_metastore_federation_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", [ + (DataprocMetastoreFederationClient, "grpc"), + (DataprocMetastoreFederationAsyncClient, "grpc_asyncio"), + (DataprocMetastoreFederationClient, "rest"), +]) +def test_dataproc_metastore_federation_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 == ( + 'metastore.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://metastore.googleapis.com' + ) + + +def test_dataproc_metastore_federation_client_get_transport_class(): + transport = DataprocMetastoreFederationClient.get_transport_class() + available_transports = [ + transports.DataprocMetastoreFederationGrpcTransport, + transports.DataprocMetastoreFederationRestTransport, + ] + assert transport in available_transports + + transport = DataprocMetastoreFederationClient.get_transport_class("grpc") + assert transport == transports.DataprocMetastoreFederationGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport, "grpc"), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio"), + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationRestTransport, "rest"), +]) +@mock.patch.object(DataprocMetastoreFederationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreFederationClient)) +@mock.patch.object(DataprocMetastoreFederationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreFederationAsyncClient)) +def test_dataproc_metastore_federation_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(DataprocMetastoreFederationClient, '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(DataprocMetastoreFederationClient, '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", [ + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport, "grpc", "true"), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport, "grpc", "false"), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationRestTransport, "rest", "true"), + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationRestTransport, "rest", "false"), +]) +@mock.patch.object(DataprocMetastoreFederationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreFederationClient)) +@mock.patch.object(DataprocMetastoreFederationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreFederationAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_dataproc_metastore_federation_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", [ + DataprocMetastoreFederationClient, DataprocMetastoreFederationAsyncClient +]) +@mock.patch.object(DataprocMetastoreFederationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreFederationClient)) +@mock.patch.object(DataprocMetastoreFederationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreFederationAsyncClient)) +def test_dataproc_metastore_federation_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", [ + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport, "grpc"), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio"), + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationRestTransport, "rest"), +]) +def test_dataproc_metastore_federation_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", [ + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport, "grpc", grpc_helpers), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationRestTransport, "rest", None), +]) +def test_dataproc_metastore_federation_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_dataproc_metastore_federation_client_client_options_from_dict(): + with mock.patch('google.cloud.metastore_v1alpha.services.dataproc_metastore_federation.transports.DataprocMetastoreFederationGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DataprocMetastoreFederationClient( + 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", [ + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport, "grpc", grpc_helpers), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_dataproc_metastore_federation_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( + "metastore.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="metastore.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.ListFederationsRequest, + dict, +]) +def test_list_federations(request_type, transport: str = 'grpc'): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore_federation.ListFederationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_federations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.ListFederationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFederationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_federations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreFederationClient( + credentials=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_federations), + '__call__') as call: + client.list_federations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.ListFederationsRequest() + +@pytest.mark.asyncio +async def test_list_federations_async(transport: str = 'grpc_asyncio', request_type=metastore_federation.ListFederationsRequest): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore_federation.ListFederationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_federations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.ListFederationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFederationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_federations_async_from_dict(): + await test_list_federations_async(request_type=dict) + + +def test_list_federations_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.ListFederationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_federations), + '__call__') as call: + call.return_value = metastore_federation.ListFederationsResponse() + client.list_federations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federations_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.ListFederationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_federations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore_federation.ListFederationsResponse()) + await client.list_federations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federations_flattened(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_federations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore_federation.ListFederationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_federations( + 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_federations_flattened_error(): + client = DataprocMetastoreFederationClient( + credentials=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_federations( + metastore_federation.ListFederationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_federations_flattened_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_federations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore_federation.ListFederationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore_federation.ListFederationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_federations( + 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_federations_flattened_error_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_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_federations( + metastore_federation.ListFederationsRequest(), + parent='parent_value', + ) + + +def test_list_federations_pager(transport_name: str = "grpc"): + client = DataprocMetastoreFederationClient( + 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_federations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + next_page_token='abc', + ), + metastore_federation.ListFederationsResponse( + federations=[], + next_page_token='def', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + ], + next_page_token='ghi', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_federations(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore_federation.Federation) + for i in results) +def test_list_federations_pages(transport_name: str = "grpc"): + client = DataprocMetastoreFederationClient( + 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_federations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + next_page_token='abc', + ), + metastore_federation.ListFederationsResponse( + federations=[], + next_page_token='def', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + ], + next_page_token='ghi', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_federations(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_federations_async_pager(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_federations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + next_page_token='abc', + ), + metastore_federation.ListFederationsResponse( + federations=[], + next_page_token='def', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + ], + next_page_token='ghi', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_federations(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, metastore_federation.Federation) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_federations_async_pages(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_federations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + next_page_token='abc', + ), + metastore_federation.ListFederationsResponse( + federations=[], + next_page_token='def', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + ], + next_page_token='ghi', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_federations(request={})).pages: # pragma: no branch + 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", [ + metastore_federation.GetFederationRequest, + dict, +]) +def test_get_federation(request_type, transport: str = 'grpc'): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore_federation.Federation( + name='name_value', + version='version_value', + endpoint_uri='endpoint_uri_value', + state=metastore_federation.Federation.State.CREATING, + state_message='state_message_value', + uid='uid_value', + ) + response = client.get_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.GetFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore_federation.Federation) + assert response.name == 'name_value' + assert response.version == 'version_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.state == metastore_federation.Federation.State.CREATING + assert response.state_message == 'state_message_value' + assert response.uid == 'uid_value' + + +def test_get_federation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreFederationClient( + credentials=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_federation), + '__call__') as call: + client.get_federation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.GetFederationRequest() + +@pytest.mark.asyncio +async def test_get_federation_async(transport: str = 'grpc_asyncio', request_type=metastore_federation.GetFederationRequest): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore_federation.Federation( + name='name_value', + version='version_value', + endpoint_uri='endpoint_uri_value', + state=metastore_federation.Federation.State.CREATING, + state_message='state_message_value', + uid='uid_value', + )) + response = await client.get_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.GetFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore_federation.Federation) + assert response.name == 'name_value' + assert response.version == 'version_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.state == metastore_federation.Federation.State.CREATING + assert response.state_message == 'state_message_value' + assert response.uid == 'uid_value' + + +@pytest.mark.asyncio +async def test_get_federation_async_from_dict(): + await test_get_federation_async(request_type=dict) + + +def test_get_federation_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.GetFederationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_federation), + '__call__') as call: + call.return_value = metastore_federation.Federation() + client.get_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federation_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.GetFederationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_federation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore_federation.Federation()) + await client.get_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federation_flattened(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore_federation.Federation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_federation( + 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_federation_flattened_error(): + client = DataprocMetastoreFederationClient( + credentials=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_federation( + metastore_federation.GetFederationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_federation_flattened_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore_federation.Federation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore_federation.Federation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_federation( + 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_federation_flattened_error_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_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_federation( + metastore_federation.GetFederationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.CreateFederationRequest, + dict, +]) +def test_create_federation(request_type, transport: str = 'grpc'): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.CreateFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_federation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreFederationClient( + credentials=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_federation), + '__call__') as call: + client.create_federation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.CreateFederationRequest() + +@pytest.mark.asyncio +async def test_create_federation_async(transport: str = 'grpc_asyncio', request_type=metastore_federation.CreateFederationRequest): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.CreateFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_federation_async_from_dict(): + await test_create_federation_async(request_type=dict) + + +def test_create_federation_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.CreateFederationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_federation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federation_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.CreateFederationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_federation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federation_flattened(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_federation( + parent='parent_value', + federation=metastore_federation.Federation(name='name_value'), + federation_id='federation_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].federation + mock_val = metastore_federation.Federation(name='name_value') + assert arg == mock_val + arg = args[0].federation_id + mock_val = 'federation_id_value' + assert arg == mock_val + + +def test_create_federation_flattened_error(): + client = DataprocMetastoreFederationClient( + credentials=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_federation( + metastore_federation.CreateFederationRequest(), + parent='parent_value', + federation=metastore_federation.Federation(name='name_value'), + federation_id='federation_id_value', + ) + +@pytest.mark.asyncio +async def test_create_federation_flattened_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_federation( + parent='parent_value', + federation=metastore_federation.Federation(name='name_value'), + federation_id='federation_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].federation + mock_val = metastore_federation.Federation(name='name_value') + assert arg == mock_val + arg = args[0].federation_id + mock_val = 'federation_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_federation_flattened_error_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_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_federation( + metastore_federation.CreateFederationRequest(), + parent='parent_value', + federation=metastore_federation.Federation(name='name_value'), + federation_id='federation_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.UpdateFederationRequest, + dict, +]) +def test_update_federation(request_type, transport: str = 'grpc'): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.UpdateFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_federation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreFederationClient( + credentials=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_federation), + '__call__') as call: + client.update_federation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.UpdateFederationRequest() + +@pytest.mark.asyncio +async def test_update_federation_async(transport: str = 'grpc_asyncio', request_type=metastore_federation.UpdateFederationRequest): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.UpdateFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_federation_async_from_dict(): + await test_update_federation_async(request_type=dict) + + +def test_update_federation_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.UpdateFederationRequest() + + request.federation.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_federation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'federation.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_federation_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.UpdateFederationRequest() + + request.federation.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_federation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'federation.name=name_value', + ) in kw['metadata'] + + +def test_update_federation_flattened(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_federation( + federation=metastore_federation.Federation(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].federation + mock_val = metastore_federation.Federation(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_federation_flattened_error(): + client = DataprocMetastoreFederationClient( + credentials=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_federation( + metastore_federation.UpdateFederationRequest(), + federation=metastore_federation.Federation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_federation_flattened_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_federation( + federation=metastore_federation.Federation(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].federation + mock_val = metastore_federation.Federation(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_federation_flattened_error_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_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_federation( + metastore_federation.UpdateFederationRequest(), + federation=metastore_federation.Federation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.DeleteFederationRequest, + dict, +]) +def test_delete_federation(request_type, transport: str = 'grpc'): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.DeleteFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_federation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreFederationClient( + credentials=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_federation), + '__call__') as call: + client.delete_federation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.DeleteFederationRequest() + +@pytest.mark.asyncio +async def test_delete_federation_async(transport: str = 'grpc_asyncio', request_type=metastore_federation.DeleteFederationRequest): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.DeleteFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_federation_async_from_dict(): + await test_delete_federation_async(request_type=dict) + + +def test_delete_federation_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.DeleteFederationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_federation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federation_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.DeleteFederationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_federation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federation_flattened(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_federation( + 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_federation_flattened_error(): + client = DataprocMetastoreFederationClient( + credentials=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_federation( + metastore_federation.DeleteFederationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_federation_flattened_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_federation( + 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_federation_flattened_error_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_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_federation( + metastore_federation.DeleteFederationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.ListFederationsRequest, + dict, +]) +def test_list_federations_rest(request_type): + client = DataprocMetastoreFederationClient( + 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 = metastore_federation.ListFederationsResponse( + 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 = metastore_federation.ListFederationsResponse.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_federations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFederationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_federations_rest_required_fields(request_type=metastore_federation.ListFederationsRequest): + transport_class = transports.DataprocMetastoreFederationRestTransport + + 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_federations._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_federations._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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore_federation.ListFederationsResponse() + # 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 = metastore_federation.ListFederationsResponse.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_federations(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_federations_rest_unset_required_fields(): + transport = transports.DataprocMetastoreFederationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_federations._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_federations_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreFederationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreFederationRestInterceptor(), + ) + client = DataprocMetastoreFederationClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "post_list_federations") as post, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "pre_list_federations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore_federation.ListFederationsRequest.pb(metastore_federation.ListFederationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore_federation.ListFederationsResponse.to_json(metastore_federation.ListFederationsResponse()) + + request = metastore_federation.ListFederationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore_federation.ListFederationsResponse() + + client.list_federations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_federations_rest_bad_request(transport: str = 'rest', request_type=metastore_federation.ListFederationsRequest): + client = DataprocMetastoreFederationClient( + 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_federations(request) + + +def test_list_federations_rest_flattened(): + client = DataprocMetastoreFederationClient( + 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 = metastore_federation.ListFederationsResponse() + + # 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 = metastore_federation.ListFederationsResponse.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_federations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=projects/*/locations/*}/federations" % client.transport._host, args[1]) + + +def test_list_federations_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreFederationClient( + 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_federations( + metastore_federation.ListFederationsRequest(), + parent='parent_value', + ) + + +def test_list_federations_rest_pager(transport: str = 'rest'): + client = DataprocMetastoreFederationClient( + 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 = ( + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + next_page_token='abc', + ), + metastore_federation.ListFederationsResponse( + federations=[], + next_page_token='def', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + ], + next_page_token='ghi', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(metastore_federation.ListFederationsResponse.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_federations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore_federation.Federation) + for i in results) + + pages = list(client.list_federations(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", [ + metastore_federation.GetFederationRequest, + dict, +]) +def test_get_federation_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/federations/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 = metastore_federation.Federation( + name='name_value', + version='version_value', + endpoint_uri='endpoint_uri_value', + state=metastore_federation.Federation.State.CREATING, + state_message='state_message_value', + uid='uid_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = metastore_federation.Federation.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_federation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore_federation.Federation) + assert response.name == 'name_value' + assert response.version == 'version_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.state == metastore_federation.Federation.State.CREATING + assert response.state_message == 'state_message_value' + assert response.uid == 'uid_value' + + +def test_get_federation_rest_required_fields(request_type=metastore_federation.GetFederationRequest): + transport_class = transports.DataprocMetastoreFederationRestTransport + + 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_federation._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_federation._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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore_federation.Federation() + # 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 = metastore_federation.Federation.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_federation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_federation_rest_unset_required_fields(): + transport = transports.DataprocMetastoreFederationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_federation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_federation_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreFederationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreFederationRestInterceptor(), + ) + client = DataprocMetastoreFederationClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "post_get_federation") as post, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "pre_get_federation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore_federation.GetFederationRequest.pb(metastore_federation.GetFederationRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore_federation.Federation.to_json(metastore_federation.Federation()) + + request = metastore_federation.GetFederationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore_federation.Federation() + + client.get_federation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_federation_rest_bad_request(transport: str = 'rest', request_type=metastore_federation.GetFederationRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/federations/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_federation(request) + + +def test_get_federation_rest_flattened(): + client = DataprocMetastoreFederationClient( + 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 = metastore_federation.Federation() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/federations/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 = metastore_federation.Federation.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_federation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=projects/*/locations/*/federations/*}" % client.transport._host, args[1]) + + +def test_get_federation_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreFederationClient( + 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_federation( + metastore_federation.GetFederationRequest(), + name='name_value', + ) + + +def test_get_federation_rest_error(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.CreateFederationRequest, + dict, +]) +def test_create_federation_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["federation"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'version': 'version_value', 'backend_metastores': {}, 'endpoint_uri': 'endpoint_uri_value', 'state': 1, 'state_message': 'state_message_value', 'uid': 'uid_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 = operations_pb2.Operation(name='operations/spam') + + # 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.create_federation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_federation_rest_required_fields(request_type=metastore_federation.CreateFederationRequest): + transport_class = transports.DataprocMetastoreFederationRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["federation_id"] = "" + 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 + assert "federationId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_federation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "federationId" in jsonified_request + assert jsonified_request["federationId"] == request_init["federation_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["federationId"] = 'federation_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_federation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("federation_id", "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' + assert "federationId" in jsonified_request + assert jsonified_request["federationId"] == 'federation_id_value' + + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_federation(request) + + expected_params = [ + ( + "federationId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_federation_rest_unset_required_fields(): + transport = transports.DataprocMetastoreFederationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_federation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("federationId", "requestId", )) & set(("parent", "federationId", "federation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_federation_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreFederationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreFederationRestInterceptor(), + ) + client = DataprocMetastoreFederationClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "post_create_federation") as post, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "pre_create_federation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore_federation.CreateFederationRequest.pb(metastore_federation.CreateFederationRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore_federation.CreateFederationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_federation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_federation_rest_bad_request(transport: str = 'rest', request_type=metastore_federation.CreateFederationRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["federation"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'version': 'version_value', 'backend_metastores': {}, 'endpoint_uri': 'endpoint_uri_value', 'state': 1, 'state_message': 'state_message_value', 'uid': 'uid_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_federation(request) + + +def test_create_federation_rest_flattened(): + client = DataprocMetastoreFederationClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # 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', + federation=metastore_federation.Federation(name='name_value'), + federation_id='federation_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_federation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=projects/*/locations/*}/federations" % client.transport._host, args[1]) + + +def test_create_federation_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreFederationClient( + 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_federation( + metastore_federation.CreateFederationRequest(), + parent='parent_value', + federation=metastore_federation.Federation(name='name_value'), + federation_id='federation_id_value', + ) + + +def test_create_federation_rest_error(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.UpdateFederationRequest, + dict, +]) +def test_update_federation_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'federation': {'name': 'projects/sample1/locations/sample2/federations/sample3'}} + request_init["federation"] = {'name': 'projects/sample1/locations/sample2/federations/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'version': 'version_value', 'backend_metastores': {}, 'endpoint_uri': 'endpoint_uri_value', 'state': 1, 'state_message': 'state_message_value', 'uid': 'uid_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 = operations_pb2.Operation(name='operations/spam') + + # 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.update_federation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_federation_rest_required_fields(request_type=metastore_federation.UpdateFederationRequest): + transport_class = transports.DataprocMetastoreFederationRestTransport + + 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_federation._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_federation._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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_federation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_federation_rest_unset_required_fields(): + transport = transports.DataprocMetastoreFederationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_federation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "federation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_federation_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreFederationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreFederationRestInterceptor(), + ) + client = DataprocMetastoreFederationClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "post_update_federation") as post, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "pre_update_federation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore_federation.UpdateFederationRequest.pb(metastore_federation.UpdateFederationRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore_federation.UpdateFederationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_federation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_federation_rest_bad_request(transport: str = 'rest', request_type=metastore_federation.UpdateFederationRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'federation': {'name': 'projects/sample1/locations/sample2/federations/sample3'}} + request_init["federation"] = {'name': 'projects/sample1/locations/sample2/federations/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'version': 'version_value', 'backend_metastores': {}, 'endpoint_uri': 'endpoint_uri_value', 'state': 1, 'state_message': 'state_message_value', 'uid': 'uid_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_federation(request) + + +def test_update_federation_rest_flattened(): + client = DataprocMetastoreFederationClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'federation': {'name': 'projects/sample1/locations/sample2/federations/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + federation=metastore_federation.Federation(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_federation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{federation.name=projects/*/locations/*/federations/*}" % client.transport._host, args[1]) + + +def test_update_federation_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreFederationClient( + 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_federation( + metastore_federation.UpdateFederationRequest(), + federation=metastore_federation.Federation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_federation_rest_error(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.DeleteFederationRequest, + dict, +]) +def test_delete_federation_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/federations/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(name='operations/spam') + + # 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.delete_federation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_federation_rest_required_fields(request_type=metastore_federation.DeleteFederationRequest): + transport_class = transports.DataprocMetastoreFederationRestTransport + + 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_federation._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_federation._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 "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # 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 = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_federation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_federation_rest_unset_required_fields(): + transport = transports.DataprocMetastoreFederationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_federation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_federation_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreFederationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreFederationRestInterceptor(), + ) + client = DataprocMetastoreFederationClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "post_delete_federation") as post, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "pre_delete_federation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore_federation.DeleteFederationRequest.pb(metastore_federation.DeleteFederationRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore_federation.DeleteFederationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_federation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_federation_rest_bad_request(transport: str = 'rest', request_type=metastore_federation.DeleteFederationRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/federations/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_federation(request) + + +def test_delete_federation_rest_flattened(): + client = DataprocMetastoreFederationClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/federations/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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_federation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=projects/*/locations/*/federations/*}" % client.transport._host, args[1]) + + +def test_delete_federation_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreFederationClient( + 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_federation( + metastore_federation.DeleteFederationRequest(), + name='name_value', + ) + + +def test_delete_federation_rest_error(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DataprocMetastoreFederationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DataprocMetastoreFederationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataprocMetastoreFederationClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DataprocMetastoreFederationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DataprocMetastoreFederationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataprocMetastoreFederationClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataprocMetastoreFederationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DataprocMetastoreFederationClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataprocMetastoreFederationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DataprocMetastoreFederationGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DataprocMetastoreFederationGrpcTransport, + transports.DataprocMetastoreFederationGrpcAsyncIOTransport, + transports.DataprocMetastoreFederationRestTransport, +]) +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 = DataprocMetastoreFederationClient.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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DataprocMetastoreFederationGrpcTransport, + ) + +def test_dataproc_metastore_federation_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DataprocMetastoreFederationTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_dataproc_metastore_federation_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.metastore_v1alpha.services.dataproc_metastore_federation.transports.DataprocMetastoreFederationTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DataprocMetastoreFederationTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_federations', + 'get_federation', + 'create_federation', + 'update_federation', + 'delete_federation', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_dataproc_metastore_federation_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.metastore_v1alpha.services.dataproc_metastore_federation.transports.DataprocMetastoreFederationTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataprocMetastoreFederationTransport( + 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_dataproc_metastore_federation_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.metastore_v1alpha.services.dataproc_metastore_federation.transports.DataprocMetastoreFederationTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataprocMetastoreFederationTransport() + adc.assert_called_once() + + +def test_dataproc_metastore_federation_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) + DataprocMetastoreFederationClient() + 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.DataprocMetastoreFederationGrpcTransport, + transports.DataprocMetastoreFederationGrpcAsyncIOTransport, + ], +) +def test_dataproc_metastore_federation_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.DataprocMetastoreFederationGrpcTransport, + transports.DataprocMetastoreFederationGrpcAsyncIOTransport, + transports.DataprocMetastoreFederationRestTransport, + ], +) +def test_dataproc_metastore_federation_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.DataprocMetastoreFederationGrpcTransport, grpc_helpers), + (transports.DataprocMetastoreFederationGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_dataproc_metastore_federation_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( + "metastore.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="metastore.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DataprocMetastoreFederationGrpcTransport, transports.DataprocMetastoreFederationGrpcAsyncIOTransport]) +def test_dataproc_metastore_federation_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_dataproc_metastore_federation_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.DataprocMetastoreFederationRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_dataproc_metastore_federation_rest_lro_client(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_dataproc_metastore_federation_host_no_port(transport_name): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='metastore.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'metastore.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://metastore.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_dataproc_metastore_federation_host_with_port(transport_name): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='metastore.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'metastore.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://metastore.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_dataproc_metastore_federation_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DataprocMetastoreFederationClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DataprocMetastoreFederationClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_federations._session + session2 = client2.transport.list_federations._session + assert session1 != session2 + session1 = client1.transport.get_federation._session + session2 = client2.transport.get_federation._session + assert session1 != session2 + session1 = client1.transport.create_federation._session + session2 = client2.transport.create_federation._session + assert session1 != session2 + session1 = client1.transport.update_federation._session + session2 = client2.transport.update_federation._session + assert session1 != session2 + session1 = client1.transport.delete_federation._session + session2 = client2.transport.delete_federation._session + assert session1 != session2 +def test_dataproc_metastore_federation_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataprocMetastoreFederationGrpcTransport( + 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_dataproc_metastore_federation_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataprocMetastoreFederationGrpcAsyncIOTransport( + 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.DataprocMetastoreFederationGrpcTransport, transports.DataprocMetastoreFederationGrpcAsyncIOTransport]) +def test_dataproc_metastore_federation_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.DataprocMetastoreFederationGrpcTransport, transports.DataprocMetastoreFederationGrpcAsyncIOTransport]) +def test_dataproc_metastore_federation_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_dataproc_metastore_federation_grpc_lro_client(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_dataproc_metastore_federation_grpc_lro_async_client(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_federation_path(): + project = "squid" + location = "clam" + federation = "whelk" + expected = "projects/{project}/locations/{location}/federations/{federation}".format(project=project, location=location, federation=federation, ) + actual = DataprocMetastoreFederationClient.federation_path(project, location, federation) + assert expected == actual + + +def test_parse_federation_path(): + expected = { + "project": "octopus", + "location": "oyster", + "federation": "nudibranch", + } + path = DataprocMetastoreFederationClient.federation_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreFederationClient.parse_federation_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DataprocMetastoreFederationClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = DataprocMetastoreFederationClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreFederationClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = DataprocMetastoreFederationClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = DataprocMetastoreFederationClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreFederationClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DataprocMetastoreFederationClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = DataprocMetastoreFederationClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreFederationClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = DataprocMetastoreFederationClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = DataprocMetastoreFederationClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreFederationClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = DataprocMetastoreFederationClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = DataprocMetastoreFederationClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreFederationClient.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.DataprocMetastoreFederationTransport, '_prep_wrapped_messages') as prep: + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DataprocMetastoreFederationTransport, '_prep_wrapped_messages') as prep: + transport_class = DataprocMetastoreFederationClient.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 = DataprocMetastoreFederationAsyncClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/services/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_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/services/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 = policy_pb2.Policy() + + # 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_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/services/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.set_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/services/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 = policy_pb2.Policy() + + # 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.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/services/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.test_iam_permissions(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/services/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 = iam_policy_pb2.TestIamPermissionsResponse() + + # 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.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationAsyncClient( + 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_get_operation(transport: str = "grpc"): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationAsyncClient( + 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationAsyncClient( + 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationAsyncClient( + 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationAsyncClient( + 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_set_iam_policy(transport: str = "grpc"): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the 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, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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", [ + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v1beta/.coveragerc b/owl-bot-staging/v1beta/.coveragerc new file mode 100644 index 0000000..6409f0c --- /dev/null +++ b/owl-bot-staging/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/metastore/__init__.py + google/cloud/metastore/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/v1beta/.flake8 b/owl-bot-staging/v1beta/.flake8 new file mode 100644 index 0000000..29227d4 --- /dev/null +++ b/owl-bot-staging/v1beta/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v1beta/MANIFEST.in b/owl-bot-staging/v1beta/MANIFEST.in new file mode 100644 index 0000000..b00fcef --- /dev/null +++ b/owl-bot-staging/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/metastore *.py +recursive-include google/cloud/metastore_v1beta *.py diff --git a/owl-bot-staging/v1beta/README.rst b/owl-bot-staging/v1beta/README.rst new file mode 100644 index 0000000..f16e3c2 --- /dev/null +++ b/owl-bot-staging/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Metastore 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 Metastore API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1beta/docs/conf.py b/owl-bot-staging/v1beta/docs/conf.py new file mode 100644 index 0000000..74eaefd --- /dev/null +++ b/owl-bot-staging/v1beta/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-dataproc-metastore 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-dataproc-metastore" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google 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-dataproc-metastore-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-dataproc-metastore.tex", + u"google-cloud-dataproc-metastore 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-dataproc-metastore", + u"Google Cloud Metastore 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-dataproc-metastore", + u"google-cloud-dataproc-metastore Documentation", + author, + "google-cloud-dataproc-metastore", + "GAPIC library for Google Cloud Metastore API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1beta/docs/index.rst b/owl-bot-staging/v1beta/docs/index.rst new file mode 100644 index 0000000..9ced08d --- /dev/null +++ b/owl-bot-staging/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + metastore_v1beta/services + metastore_v1beta/types diff --git a/owl-bot-staging/v1beta/docs/metastore_v1beta/dataproc_metastore.rst b/owl-bot-staging/v1beta/docs/metastore_v1beta/dataproc_metastore.rst new file mode 100644 index 0000000..04c8322 --- /dev/null +++ b/owl-bot-staging/v1beta/docs/metastore_v1beta/dataproc_metastore.rst @@ -0,0 +1,10 @@ +DataprocMetastore +----------------------------------- + +.. automodule:: google.cloud.metastore_v1beta.services.dataproc_metastore + :members: + :inherited-members: + +.. automodule:: google.cloud.metastore_v1beta.services.dataproc_metastore.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta/docs/metastore_v1beta/dataproc_metastore_federation.rst b/owl-bot-staging/v1beta/docs/metastore_v1beta/dataproc_metastore_federation.rst new file mode 100644 index 0000000..5a09d31 --- /dev/null +++ b/owl-bot-staging/v1beta/docs/metastore_v1beta/dataproc_metastore_federation.rst @@ -0,0 +1,10 @@ +DataprocMetastoreFederation +--------------------------------------------- + +.. automodule:: google.cloud.metastore_v1beta.services.dataproc_metastore_federation + :members: + :inherited-members: + +.. automodule:: google.cloud.metastore_v1beta.services.dataproc_metastore_federation.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta/docs/metastore_v1beta/services.rst b/owl-bot-staging/v1beta/docs/metastore_v1beta/services.rst new file mode 100644 index 0000000..5e9f5ae --- /dev/null +++ b/owl-bot-staging/v1beta/docs/metastore_v1beta/services.rst @@ -0,0 +1,7 @@ +Services for Google Cloud Metastore v1beta API +============================================== +.. toctree:: + :maxdepth: 2 + + dataproc_metastore + dataproc_metastore_federation diff --git a/owl-bot-staging/v1beta/docs/metastore_v1beta/types.rst b/owl-bot-staging/v1beta/docs/metastore_v1beta/types.rst new file mode 100644 index 0000000..c52aabe --- /dev/null +++ b/owl-bot-staging/v1beta/docs/metastore_v1beta/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Metastore v1beta API +=========================================== + +.. automodule:: google.cloud.metastore_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v1beta/google/cloud/metastore/__init__.py b/owl-bot-staging/v1beta/google/cloud/metastore/__init__.py new file mode 100644 index 0000000..a20e2ad --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore/__init__.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.metastore import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.metastore_v1beta.services.dataproc_metastore.client import DataprocMetastoreClient +from google.cloud.metastore_v1beta.services.dataproc_metastore.async_client import DataprocMetastoreAsyncClient +from google.cloud.metastore_v1beta.services.dataproc_metastore_federation.client import DataprocMetastoreFederationClient +from google.cloud.metastore_v1beta.services.dataproc_metastore_federation.async_client import DataprocMetastoreFederationAsyncClient + +from google.cloud.metastore_v1beta.types.metastore import AlterMetadataResourceLocationRequest +from google.cloud.metastore_v1beta.types.metastore import AlterMetadataResourceLocationResponse +from google.cloud.metastore_v1beta.types.metastore import AuxiliaryVersionConfig +from google.cloud.metastore_v1beta.types.metastore import Backup +from google.cloud.metastore_v1beta.types.metastore import CreateBackupRequest +from google.cloud.metastore_v1beta.types.metastore import CreateMetadataImportRequest +from google.cloud.metastore_v1beta.types.metastore import CreateServiceRequest +from google.cloud.metastore_v1beta.types.metastore import DatabaseDumpSpec +from google.cloud.metastore_v1beta.types.metastore import DataCatalogConfig +from google.cloud.metastore_v1beta.types.metastore import DataplexConfig +from google.cloud.metastore_v1beta.types.metastore import DeleteBackupRequest +from google.cloud.metastore_v1beta.types.metastore import DeleteServiceRequest +from google.cloud.metastore_v1beta.types.metastore import EncryptionConfig +from google.cloud.metastore_v1beta.types.metastore import ExportMetadataRequest +from google.cloud.metastore_v1beta.types.metastore import GetBackupRequest +from google.cloud.metastore_v1beta.types.metastore import GetMetadataImportRequest +from google.cloud.metastore_v1beta.types.metastore import GetServiceRequest +from google.cloud.metastore_v1beta.types.metastore import HiveMetastoreConfig +from google.cloud.metastore_v1beta.types.metastore import KerberosConfig +from google.cloud.metastore_v1beta.types.metastore import Lake +from google.cloud.metastore_v1beta.types.metastore import ListBackupsRequest +from google.cloud.metastore_v1beta.types.metastore import ListBackupsResponse +from google.cloud.metastore_v1beta.types.metastore import ListMetadataImportsRequest +from google.cloud.metastore_v1beta.types.metastore import ListMetadataImportsResponse +from google.cloud.metastore_v1beta.types.metastore import ListServicesRequest +from google.cloud.metastore_v1beta.types.metastore import ListServicesResponse +from google.cloud.metastore_v1beta.types.metastore import LocationMetadata +from google.cloud.metastore_v1beta.types.metastore import MaintenanceWindow +from google.cloud.metastore_v1beta.types.metastore import MetadataExport +from google.cloud.metastore_v1beta.types.metastore import MetadataImport +from google.cloud.metastore_v1beta.types.metastore import MetadataIntegration +from google.cloud.metastore_v1beta.types.metastore import MetadataManagementActivity +from google.cloud.metastore_v1beta.types.metastore import MoveTableToDatabaseRequest +from google.cloud.metastore_v1beta.types.metastore import MoveTableToDatabaseResponse +from google.cloud.metastore_v1beta.types.metastore import NetworkConfig +from google.cloud.metastore_v1beta.types.metastore import OperationMetadata +from google.cloud.metastore_v1beta.types.metastore import QueryMetadataRequest +from google.cloud.metastore_v1beta.types.metastore import QueryMetadataResponse +from google.cloud.metastore_v1beta.types.metastore import RemoveIamPolicyRequest +from google.cloud.metastore_v1beta.types.metastore import RemoveIamPolicyResponse +from google.cloud.metastore_v1beta.types.metastore import Restore +from google.cloud.metastore_v1beta.types.metastore import RestoreServiceRequest +from google.cloud.metastore_v1beta.types.metastore import Secret +from google.cloud.metastore_v1beta.types.metastore import Service +from google.cloud.metastore_v1beta.types.metastore import TelemetryConfig +from google.cloud.metastore_v1beta.types.metastore import UpdateMetadataImportRequest +from google.cloud.metastore_v1beta.types.metastore import UpdateServiceRequest +from google.cloud.metastore_v1beta.types.metastore_federation import BackendMetastore +from google.cloud.metastore_v1beta.types.metastore_federation import CreateFederationRequest +from google.cloud.metastore_v1beta.types.metastore_federation import DeleteFederationRequest +from google.cloud.metastore_v1beta.types.metastore_federation import Federation +from google.cloud.metastore_v1beta.types.metastore_federation import GetFederationRequest +from google.cloud.metastore_v1beta.types.metastore_federation import ListFederationsRequest +from google.cloud.metastore_v1beta.types.metastore_federation import ListFederationsResponse +from google.cloud.metastore_v1beta.types.metastore_federation import UpdateFederationRequest + +__all__ = ('DataprocMetastoreClient', + 'DataprocMetastoreAsyncClient', + 'DataprocMetastoreFederationClient', + 'DataprocMetastoreFederationAsyncClient', + 'AlterMetadataResourceLocationRequest', + 'AlterMetadataResourceLocationResponse', + 'AuxiliaryVersionConfig', + 'Backup', + 'CreateBackupRequest', + 'CreateMetadataImportRequest', + 'CreateServiceRequest', + 'DatabaseDumpSpec', + 'DataCatalogConfig', + 'DataplexConfig', + 'DeleteBackupRequest', + 'DeleteServiceRequest', + 'EncryptionConfig', + 'ExportMetadataRequest', + 'GetBackupRequest', + 'GetMetadataImportRequest', + 'GetServiceRequest', + 'HiveMetastoreConfig', + 'KerberosConfig', + 'Lake', + 'ListBackupsRequest', + 'ListBackupsResponse', + 'ListMetadataImportsRequest', + 'ListMetadataImportsResponse', + 'ListServicesRequest', + 'ListServicesResponse', + 'LocationMetadata', + 'MaintenanceWindow', + 'MetadataExport', + 'MetadataImport', + 'MetadataIntegration', + 'MetadataManagementActivity', + 'MoveTableToDatabaseRequest', + 'MoveTableToDatabaseResponse', + 'NetworkConfig', + 'OperationMetadata', + 'QueryMetadataRequest', + 'QueryMetadataResponse', + 'RemoveIamPolicyRequest', + 'RemoveIamPolicyResponse', + 'Restore', + 'RestoreServiceRequest', + 'Secret', + 'Service', + 'TelemetryConfig', + 'UpdateMetadataImportRequest', + 'UpdateServiceRequest', + 'BackendMetastore', + 'CreateFederationRequest', + 'DeleteFederationRequest', + 'Federation', + 'GetFederationRequest', + 'ListFederationsRequest', + 'ListFederationsResponse', + 'UpdateFederationRequest', +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore/gapic_version.py b/owl-bot-staging/v1beta/google/cloud/metastore/gapic_version.py new file mode 100644 index 0000000..405b1ce --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1beta/google/cloud/metastore/py.typed b/owl-bot-staging/v1beta/google/cloud/metastore/py.typed new file mode 100644 index 0000000..f949c43 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-dataproc-metastore package uses inline types. diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/__init__.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/__init__.py new file mode 100644 index 0000000..0e9a070 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/__init__.py @@ -0,0 +1,142 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.metastore_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.dataproc_metastore import DataprocMetastoreClient +from .services.dataproc_metastore import DataprocMetastoreAsyncClient +from .services.dataproc_metastore_federation import DataprocMetastoreFederationClient +from .services.dataproc_metastore_federation import DataprocMetastoreFederationAsyncClient + +from .types.metastore import AlterMetadataResourceLocationRequest +from .types.metastore import AlterMetadataResourceLocationResponse +from .types.metastore import AuxiliaryVersionConfig +from .types.metastore import Backup +from .types.metastore import CreateBackupRequest +from .types.metastore import CreateMetadataImportRequest +from .types.metastore import CreateServiceRequest +from .types.metastore import DatabaseDumpSpec +from .types.metastore import DataCatalogConfig +from .types.metastore import DataplexConfig +from .types.metastore import DeleteBackupRequest +from .types.metastore import DeleteServiceRequest +from .types.metastore import EncryptionConfig +from .types.metastore import ExportMetadataRequest +from .types.metastore import GetBackupRequest +from .types.metastore import GetMetadataImportRequest +from .types.metastore import GetServiceRequest +from .types.metastore import HiveMetastoreConfig +from .types.metastore import KerberosConfig +from .types.metastore import Lake +from .types.metastore import ListBackupsRequest +from .types.metastore import ListBackupsResponse +from .types.metastore import ListMetadataImportsRequest +from .types.metastore import ListMetadataImportsResponse +from .types.metastore import ListServicesRequest +from .types.metastore import ListServicesResponse +from .types.metastore import LocationMetadata +from .types.metastore import MaintenanceWindow +from .types.metastore import MetadataExport +from .types.metastore import MetadataImport +from .types.metastore import MetadataIntegration +from .types.metastore import MetadataManagementActivity +from .types.metastore import MoveTableToDatabaseRequest +from .types.metastore import MoveTableToDatabaseResponse +from .types.metastore import NetworkConfig +from .types.metastore import OperationMetadata +from .types.metastore import QueryMetadataRequest +from .types.metastore import QueryMetadataResponse +from .types.metastore import RemoveIamPolicyRequest +from .types.metastore import RemoveIamPolicyResponse +from .types.metastore import Restore +from .types.metastore import RestoreServiceRequest +from .types.metastore import Secret +from .types.metastore import Service +from .types.metastore import TelemetryConfig +from .types.metastore import UpdateMetadataImportRequest +from .types.metastore import UpdateServiceRequest +from .types.metastore_federation import BackendMetastore +from .types.metastore_federation import CreateFederationRequest +from .types.metastore_federation import DeleteFederationRequest +from .types.metastore_federation import Federation +from .types.metastore_federation import GetFederationRequest +from .types.metastore_federation import ListFederationsRequest +from .types.metastore_federation import ListFederationsResponse +from .types.metastore_federation import UpdateFederationRequest + +__all__ = ( + 'DataprocMetastoreAsyncClient', + 'DataprocMetastoreFederationAsyncClient', +'AlterMetadataResourceLocationRequest', +'AlterMetadataResourceLocationResponse', +'AuxiliaryVersionConfig', +'BackendMetastore', +'Backup', +'CreateBackupRequest', +'CreateFederationRequest', +'CreateMetadataImportRequest', +'CreateServiceRequest', +'DataCatalogConfig', +'DatabaseDumpSpec', +'DataplexConfig', +'DataprocMetastoreClient', +'DataprocMetastoreFederationClient', +'DeleteBackupRequest', +'DeleteFederationRequest', +'DeleteServiceRequest', +'EncryptionConfig', +'ExportMetadataRequest', +'Federation', +'GetBackupRequest', +'GetFederationRequest', +'GetMetadataImportRequest', +'GetServiceRequest', +'HiveMetastoreConfig', +'KerberosConfig', +'Lake', +'ListBackupsRequest', +'ListBackupsResponse', +'ListFederationsRequest', +'ListFederationsResponse', +'ListMetadataImportsRequest', +'ListMetadataImportsResponse', +'ListServicesRequest', +'ListServicesResponse', +'LocationMetadata', +'MaintenanceWindow', +'MetadataExport', +'MetadataImport', +'MetadataIntegration', +'MetadataManagementActivity', +'MoveTableToDatabaseRequest', +'MoveTableToDatabaseResponse', +'NetworkConfig', +'OperationMetadata', +'QueryMetadataRequest', +'QueryMetadataResponse', +'RemoveIamPolicyRequest', +'RemoveIamPolicyResponse', +'Restore', +'RestoreServiceRequest', +'Secret', +'Service', +'TelemetryConfig', +'UpdateFederationRequest', +'UpdateMetadataImportRequest', +'UpdateServiceRequest', +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/gapic_metadata.json b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/gapic_metadata.json new file mode 100644 index 0000000..4694c1d --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/gapic_metadata.json @@ -0,0 +1,407 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.metastore_v1beta", + "protoPackage": "google.cloud.metastore.v1beta", + "schema": "1.0", + "services": { + "DataprocMetastore": { + "clients": { + "grpc": { + "libraryClient": "DataprocMetastoreClient", + "rpcs": { + "AlterMetadataResourceLocation": { + "methods": [ + "alter_metadata_resource_location" + ] + }, + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateMetadataImport": { + "methods": [ + "create_metadata_import" + ] + }, + "CreateService": { + "methods": [ + "create_service" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "ExportMetadata": { + "methods": [ + "export_metadata" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetMetadataImport": { + "methods": [ + "get_metadata_import" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListMetadataImports": { + "methods": [ + "list_metadata_imports" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "MoveTableToDatabase": { + "methods": [ + "move_table_to_database" + ] + }, + "QueryMetadata": { + "methods": [ + "query_metadata" + ] + }, + "RemoveIamPolicy": { + "methods": [ + "remove_iam_policy" + ] + }, + "RestoreService": { + "methods": [ + "restore_service" + ] + }, + "UpdateMetadataImport": { + "methods": [ + "update_metadata_import" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DataprocMetastoreAsyncClient", + "rpcs": { + "AlterMetadataResourceLocation": { + "methods": [ + "alter_metadata_resource_location" + ] + }, + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateMetadataImport": { + "methods": [ + "create_metadata_import" + ] + }, + "CreateService": { + "methods": [ + "create_service" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "ExportMetadata": { + "methods": [ + "export_metadata" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetMetadataImport": { + "methods": [ + "get_metadata_import" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListMetadataImports": { + "methods": [ + "list_metadata_imports" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "MoveTableToDatabase": { + "methods": [ + "move_table_to_database" + ] + }, + "QueryMetadata": { + "methods": [ + "query_metadata" + ] + }, + "RemoveIamPolicy": { + "methods": [ + "remove_iam_policy" + ] + }, + "RestoreService": { + "methods": [ + "restore_service" + ] + }, + "UpdateMetadataImport": { + "methods": [ + "update_metadata_import" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + }, + "rest": { + "libraryClient": "DataprocMetastoreClient", + "rpcs": { + "AlterMetadataResourceLocation": { + "methods": [ + "alter_metadata_resource_location" + ] + }, + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateMetadataImport": { + "methods": [ + "create_metadata_import" + ] + }, + "CreateService": { + "methods": [ + "create_service" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "ExportMetadata": { + "methods": [ + "export_metadata" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetMetadataImport": { + "methods": [ + "get_metadata_import" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListMetadataImports": { + "methods": [ + "list_metadata_imports" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "MoveTableToDatabase": { + "methods": [ + "move_table_to_database" + ] + }, + "QueryMetadata": { + "methods": [ + "query_metadata" + ] + }, + "RemoveIamPolicy": { + "methods": [ + "remove_iam_policy" + ] + }, + "RestoreService": { + "methods": [ + "restore_service" + ] + }, + "UpdateMetadataImport": { + "methods": [ + "update_metadata_import" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + } + } + }, + "DataprocMetastoreFederation": { + "clients": { + "grpc": { + "libraryClient": "DataprocMetastoreFederationClient", + "rpcs": { + "CreateFederation": { + "methods": [ + "create_federation" + ] + }, + "DeleteFederation": { + "methods": [ + "delete_federation" + ] + }, + "GetFederation": { + "methods": [ + "get_federation" + ] + }, + "ListFederations": { + "methods": [ + "list_federations" + ] + }, + "UpdateFederation": { + "methods": [ + "update_federation" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DataprocMetastoreFederationAsyncClient", + "rpcs": { + "CreateFederation": { + "methods": [ + "create_federation" + ] + }, + "DeleteFederation": { + "methods": [ + "delete_federation" + ] + }, + "GetFederation": { + "methods": [ + "get_federation" + ] + }, + "ListFederations": { + "methods": [ + "list_federations" + ] + }, + "UpdateFederation": { + "methods": [ + "update_federation" + ] + } + } + }, + "rest": { + "libraryClient": "DataprocMetastoreFederationClient", + "rpcs": { + "CreateFederation": { + "methods": [ + "create_federation" + ] + }, + "DeleteFederation": { + "methods": [ + "delete_federation" + ] + }, + "GetFederation": { + "methods": [ + "get_federation" + ] + }, + "ListFederations": { + "methods": [ + "list_federations" + ] + }, + "UpdateFederation": { + "methods": [ + "update_federation" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/gapic_version.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/gapic_version.py new file mode 100644 index 0000000..405b1ce --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/py.typed b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/py.typed new file mode 100644 index 0000000..f949c43 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-dataproc-metastore package uses inline types. diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/__init__.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/__init__.py new file mode 100644 index 0000000..e8e1c38 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/__init__.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/__init__.py new file mode 100644 index 0000000..fb93e40 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import DataprocMetastoreClient +from .async_client import DataprocMetastoreAsyncClient + +__all__ = ( + 'DataprocMetastoreClient', + 'DataprocMetastoreAsyncClient', +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/async_client.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/async_client.py new file mode 100644 index 0000000..1a5dd96 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/async_client.py @@ -0,0 +1,3004 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.metastore_v1beta import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1beta.services.dataproc_metastore import pagers +from google.cloud.metastore_v1beta.types import metastore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DataprocMetastoreTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DataprocMetastoreGrpcAsyncIOTransport +from .client import DataprocMetastoreClient + + +class DataprocMetastoreAsyncClient: + """Configures and manages metastore services. Metastore services are + fully managed, highly available, autoscaled, autohealing, OSS-native + deployments of technical metadata management software. Each + metastore service exposes a network endpoint through which metadata + queries are served. Metadata queries can originate from a variety of + sources, including Apache Hive, Apache Presto, and Apache Spark. + + The Dataproc Metastore API defines the following resource model: + + - The service works with a collection of Google Cloud projects, + named: ``/projects/*`` + + - Each project has a collection of available locations, named: + ``/locations/*`` (a location must refer to a Google Cloud + ``region``) + + - Each location has a collection of services, named: + ``/services/*`` + + - Dataproc Metastore services are resources with names of the form: + + ``/projects/{project_number}/locations/{location_id}/services/{service_id}``. + """ + + _client: DataprocMetastoreClient + + DEFAULT_ENDPOINT = DataprocMetastoreClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DataprocMetastoreClient.DEFAULT_MTLS_ENDPOINT + + backup_path = staticmethod(DataprocMetastoreClient.backup_path) + parse_backup_path = staticmethod(DataprocMetastoreClient.parse_backup_path) + lake_path = staticmethod(DataprocMetastoreClient.lake_path) + parse_lake_path = staticmethod(DataprocMetastoreClient.parse_lake_path) + metadata_import_path = staticmethod(DataprocMetastoreClient.metadata_import_path) + parse_metadata_import_path = staticmethod(DataprocMetastoreClient.parse_metadata_import_path) + network_path = staticmethod(DataprocMetastoreClient.network_path) + parse_network_path = staticmethod(DataprocMetastoreClient.parse_network_path) + service_path = staticmethod(DataprocMetastoreClient.service_path) + parse_service_path = staticmethod(DataprocMetastoreClient.parse_service_path) + subnetwork_path = staticmethod(DataprocMetastoreClient.subnetwork_path) + parse_subnetwork_path = staticmethod(DataprocMetastoreClient.parse_subnetwork_path) + common_billing_account_path = staticmethod(DataprocMetastoreClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DataprocMetastoreClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DataprocMetastoreClient.common_folder_path) + parse_common_folder_path = staticmethod(DataprocMetastoreClient.parse_common_folder_path) + common_organization_path = staticmethod(DataprocMetastoreClient.common_organization_path) + parse_common_organization_path = staticmethod(DataprocMetastoreClient.parse_common_organization_path) + common_project_path = staticmethod(DataprocMetastoreClient.common_project_path) + parse_common_project_path = staticmethod(DataprocMetastoreClient.parse_common_project_path) + common_location_path = staticmethod(DataprocMetastoreClient.common_location_path) + parse_common_location_path = staticmethod(DataprocMetastoreClient.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: + DataprocMetastoreAsyncClient: The constructed client. + """ + return DataprocMetastoreClient.from_service_account_info.__func__(DataprocMetastoreAsyncClient, 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: + DataprocMetastoreAsyncClient: The constructed client. + """ + return DataprocMetastoreClient.from_service_account_file.__func__(DataprocMetastoreAsyncClient, 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 DataprocMetastoreClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DataprocMetastoreTransport: + """Returns the transport used by the client instance. + + Returns: + DataprocMetastoreTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DataprocMetastoreClient).get_transport_class, type(DataprocMetastoreClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DataprocMetastoreTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dataproc metastore 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, ~.DataprocMetastoreTransport]): 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 = DataprocMetastoreClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_services(self, + request: Optional[Union[metastore.ListServicesRequest, 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.ListServicesAsyncPager: + r"""Lists services in a 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 metastore_v1beta + + async def sample_list_services(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.ListServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.ListServicesRequest, dict]]): + The request object. Request message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1beta.DataprocMetastore.ListServices]. + parent (:class:`str`): + Required. The relative resource name of the location of + metastore services to list, in the following form: + + ``projects/{project_number}/locations/{location_id}``. + + 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.metastore_v1beta.services.dataproc_metastore.pagers.ListServicesAsyncPager: + Response message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1beta.DataprocMetastore.ListServices]. + + 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 = metastore.ListServicesRequest(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_services, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListServicesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_service(self, + request: Optional[Union[metastore.GetServiceRequest, 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]] = (), + ) -> metastore.Service: + r"""Gets the details of a single service. + + .. 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 metastore_v1beta + + async def sample_get_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.GetServiceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_service(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.GetServiceRequest, dict]]): + The request object. Request message for + [DataprocMetastore.GetService][google.cloud.metastore.v1beta.DataprocMetastore.GetService]. + name (:class:`str`): + Required. The relative resource name of the metastore + service to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + 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.metastore_v1beta.types.Service: + A managed metastore service that + serves metadata queries. + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 = metastore.GetServiceRequest(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_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_service(self, + request: Optional[Union[metastore.CreateServiceRequest, dict]] = None, + *, + parent: Optional[str] = None, + service: Optional[metastore.Service] = None, + service_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a metastore service in a 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 metastore_v1beta + + async def sample_create_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.CreateServiceRequest( + parent="parent_value", + service_id="service_id_value", + ) + + # Make the request + operation = client.create_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.CreateServiceRequest, dict]]): + The request object. Request message for + [DataprocMetastore.CreateService][google.cloud.metastore.v1beta.DataprocMetastore.CreateService]. + parent (:class:`str`): + Required. The relative resource name of the location in + which to create a metastore service, in the following + form: + + ``projects/{project_number}/locations/{location_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service (:class:`google.cloud.metastore_v1beta.types.Service`): + Required. The Metastore service to create. The ``name`` + field is ignored. The ID of the created metastore + service must be provided in the request's ``service_id`` + field. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_id (:class:`str`): + Required. The ID of the metastore + service, which is used as the final + component of the metastore service's + name. + This value must be between 2 and 63 + characters long inclusive, begin with a + letter, end with a letter or number, and + consist of alpha-numeric ASCII + characters or hyphens. + + This corresponds to the ``service_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1beta.types.Service` A + managed metastore service that serves metadata queries. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, service, service_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = metastore.CreateServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if service is not None: + request.service = service + if service_id is not None: + request.service_id = service_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_service, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.Service, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_service(self, + request: Optional[Union[metastore.UpdateServiceRequest, dict]] = None, + *, + service: Optional[metastore.Service] = 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single service. + + .. 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 metastore_v1beta + + async def sample_update_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.UpdateServiceRequest( + ) + + # Make the request + operation = client.update_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.UpdateServiceRequest, dict]]): + The request object. Request message for + [DataprocMetastore.UpdateService][google.cloud.metastore.v1beta.DataprocMetastore.UpdateService]. + service (:class:`google.cloud.metastore_v1beta.types.Service`): + Required. The metastore service to update. The server + only merges fields in the service if they are specified + in ``update_mask``. + + The metastore service's ``name`` field is used to + identify the metastore service to be updated. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. A field mask used to specify the fields to be + overwritten in the metastore service resource by the + update. Fields specified in the ``update_mask`` are + relative to the resource (not to the full request). A + field is overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1beta.types.Service` A + managed metastore service that serves metadata queries. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, 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 = metastore.UpdateServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if service is not None: + request.service = service + 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_service, + 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(( + ("service.name", request.service.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.Service, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_service(self, + request: Optional[Union[metastore.DeleteServiceRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single service. + + .. 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 metastore_v1beta + + async def sample_delete_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.DeleteServiceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.DeleteServiceRequest, dict]]): + The request object. Request message for + [DataprocMetastore.DeleteService][google.cloud.metastore.v1beta.DataprocMetastore.DeleteService]. + name (:class:`str`): + Required. The relative resource name of the metastore + service to delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 = metastore.DeleteServiceRequest(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_service, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_metadata_imports(self, + request: Optional[Union[metastore.ListMetadataImportsRequest, 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.ListMetadataImportsAsyncPager: + r"""Lists imports in a service. + + .. 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 metastore_v1beta + + async def sample_list_metadata_imports(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.ListMetadataImportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_metadata_imports(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.ListMetadataImportsRequest, dict]]): + The request object. Request message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1beta.DataprocMetastore.ListMetadataImports]. + parent (:class:`str`): + Required. The relative resource name of the service + whose metadata imports to list, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports``. + + 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.metastore_v1beta.services.dataproc_metastore.pagers.ListMetadataImportsAsyncPager: + Response message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1beta.DataprocMetastore.ListMetadataImports]. + + 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 = metastore.ListMetadataImportsRequest(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_metadata_imports, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMetadataImportsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_metadata_import(self, + request: Optional[Union[metastore.GetMetadataImportRequest, 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]] = (), + ) -> metastore.MetadataImport: + r"""Gets details of a single import. + + .. 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 metastore_v1beta + + async def sample_get_metadata_import(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.GetMetadataImportRequest( + name="name_value", + ) + + # Make the request + response = await client.get_metadata_import(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.GetMetadataImportRequest, dict]]): + The request object. Request message for + [DataprocMetastore.GetMetadataImport][google.cloud.metastore.v1beta.DataprocMetastore.GetMetadataImport]. + name (:class:`str`): + Required. The relative resource name of the metadata + import to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports/{import_id}``. + + 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.metastore_v1beta.types.MetadataImport: + A metastore resource that imports + 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 = metastore.GetMetadataImportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_metadata_import, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_metadata_import(self, + request: Optional[Union[metastore.CreateMetadataImportRequest, dict]] = None, + *, + parent: Optional[str] = None, + metadata_import: Optional[metastore.MetadataImport] = None, + metadata_import_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new MetadataImport 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 metastore_v1beta + + async def sample_create_metadata_import(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.CreateMetadataImportRequest( + parent="parent_value", + metadata_import_id="metadata_import_id_value", + ) + + # Make the request + operation = client.create_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.CreateMetadataImportRequest, dict]]): + The request object. Request message for + [DataprocMetastore.CreateMetadataImport][google.cloud.metastore.v1beta.DataprocMetastore.CreateMetadataImport]. + parent (:class:`str`): + Required. The relative resource name of the service in + which to create a metastore import, in the following + form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + metadata_import (:class:`google.cloud.metastore_v1beta.types.MetadataImport`): + Required. The metadata import to create. The ``name`` + field is ignored. The ID of the created metadata import + must be provided in the request's ``metadata_import_id`` + field. + + This corresponds to the ``metadata_import`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + metadata_import_id (:class:`str`): + Required. The ID of the metadata + import, which is used as the final + component of the metadata import's name. + This value must be between 1 and 64 + characters long, begin with a letter, + end with a letter or number, and consist + of alpha-numeric ASCII characters or + hyphens. + + This corresponds to the ``metadata_import_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1beta.types.MetadataImport` + A metastore resource that imports 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([parent, metadata_import, metadata_import_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = metastore.CreateMetadataImportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if metadata_import is not None: + request.metadata_import = metadata_import + if metadata_import_id is not None: + request.metadata_import_id = metadata_import_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_metadata_import, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.MetadataImport, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_metadata_import(self, + request: Optional[Union[metastore.UpdateMetadataImportRequest, dict]] = None, + *, + metadata_import: Optional[metastore.MetadataImport] = 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a single import. + Only the description field of MetadataImport is + supported to be updated. + + .. 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 metastore_v1beta + + async def sample_update_metadata_import(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.UpdateMetadataImportRequest( + ) + + # Make the request + operation = client.update_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.UpdateMetadataImportRequest, dict]]): + The request object. Request message for + [DataprocMetastore.UpdateMetadataImport][google.cloud.metastore.v1beta.DataprocMetastore.UpdateMetadataImport]. + metadata_import (:class:`google.cloud.metastore_v1beta.types.MetadataImport`): + Required. The metadata import to update. The server only + merges fields in the import if they are specified in + ``update_mask``. + + The metadata import's ``name`` field is used to identify + the metastore import to be updated. + + This corresponds to the ``metadata_import`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. A field mask used to specify the fields to be + overwritten in the metadata import resource by the + update. Fields specified in the ``update_mask`` are + relative to the resource (not to the full request). A + field is overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1beta.types.MetadataImport` + A metastore resource that imports 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([metadata_import, 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 = metastore.UpdateMetadataImportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if metadata_import is not None: + request.metadata_import = metadata_import + 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_metadata_import, + 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(( + ("metadata_import.name", request.metadata_import.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.MetadataImport, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def export_metadata(self, + request: Optional[Union[metastore.ExportMetadataRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports metadata from a service. + + .. 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 metastore_v1beta + + async def sample_export_metadata(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.ExportMetadataRequest( + destination_gcs_folder="destination_gcs_folder_value", + service="service_value", + ) + + # Make the request + operation = client.export_metadata(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.ExportMetadataRequest, dict]]): + The request object. Request message for + [DataprocMetastore.ExportMetadata][google.cloud.metastore.v1beta.DataprocMetastore.ExportMetadata]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1beta.types.MetadataExport` + The details of a metadata export operation. + + """ + # Create or coerce a protobuf request object. + request = metastore.ExportMetadataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_metadata, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service", request.service), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.MetadataExport, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def restore_service(self, + request: Optional[Union[metastore.RestoreServiceRequest, dict]] = None, + *, + service: Optional[str] = None, + backup: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Restores a service from a backup. + + .. 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 metastore_v1beta + + async def sample_restore_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.RestoreServiceRequest( + service="service_value", + backup="backup_value", + ) + + # Make the request + operation = client.restore_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.RestoreServiceRequest, dict]]): + The request object. Request message for [DataprocMetastore.Restore][]. + service (:class:`str`): + Required. The relative resource name of the metastore + service to run restore, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup (:class:`str`): + Required. The relative resource name of the metastore + service backup to restore from, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1beta.types.Restore` The + details of a metadata restore operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, backup]) + if request is 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 = metastore.RestoreServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if service is not None: + request.service = service + if backup is not None: + request.backup = backup + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.restore_service, + 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(( + ("service", request.service), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.Restore, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_backups(self, + request: Optional[Union[metastore.ListBackupsRequest, 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.ListBackupsAsyncPager: + r"""Lists backups in a service. + + .. 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 metastore_v1beta + + async def sample_list_backups(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.ListBackupsRequest, dict]]): + The request object. Request message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1beta.DataprocMetastore.ListBackups]. + parent (:class:`str`): + Required. The relative resource name of the service + whose backups to list, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups``. + + 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.metastore_v1beta.services.dataproc_metastore.pagers.ListBackupsAsyncPager: + Response message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1beta.DataprocMetastore.ListBackups]. + + 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 = metastore.ListBackupsRequest(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_backups, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListBackupsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_backup(self, + request: Optional[Union[metastore.GetBackupRequest, 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]] = (), + ) -> metastore.Backup: + r"""Gets details of a single backup. + + .. 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 metastore_v1beta + + async def sample_get_backup(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.GetBackupRequest, dict]]): + The request object. Request message for + [DataprocMetastore.GetBackup][google.cloud.metastore.v1beta.DataprocMetastore.GetBackup]. + name (:class:`str`): + Required. The relative resource name of the backup to + retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + + 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.metastore_v1beta.types.Backup: + The details of a backup resource. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = metastore.GetBackupRequest(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_backup, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_backup(self, + request: Optional[Union[metastore.CreateBackupRequest, dict]] = None, + *, + parent: Optional[str] = None, + backup: Optional[metastore.Backup] = None, + backup_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new backup 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 metastore_v1beta + + async def sample_create_backup(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + ) + + # Make the request + operation = client.create_backup(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.CreateBackupRequest, dict]]): + The request object. Request message for + [DataprocMetastore.CreateBackup][google.cloud.metastore.v1beta.DataprocMetastore.CreateBackup]. + parent (:class:`str`): + Required. The relative resource name of the service in + which to create a backup of the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup (:class:`google.cloud.metastore_v1beta.types.Backup`): + Required. The backup to create. The ``name`` field is + ignored. The ID of the created backup must be provided + in the request's ``backup_id`` field. + + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_id (:class:`str`): + Required. The ID of the backup, which + is used as the final component of the + backup's name. + This value must be between 1 and 64 + characters long, begin with a letter, + end with a letter or number, and consist + of alpha-numeric ASCII characters or + hyphens. + + This corresponds to the ``backup_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1beta.types.Backup` The + details of a backup resource. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, backup, backup_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = metastore.CreateBackupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if backup is not None: + request.backup = backup + if backup_id is not None: + request.backup_id = backup_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_backup, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.Backup, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_backup(self, + request: Optional[Union[metastore.DeleteBackupRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single backup. + + .. 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 metastore_v1beta + + async def sample_delete_backup(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.DeleteBackupRequest, dict]]): + The request object. Request message for + [DataprocMetastore.DeleteBackup][google.cloud.metastore.v1beta.DataprocMetastore.DeleteBackup]. + name (:class:`str`): + Required. The relative resource name of the backup to + delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 = metastore.DeleteBackupRequest(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_backup, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def remove_iam_policy(self, + request: Optional[Union[metastore.RemoveIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> metastore.RemoveIamPolicyResponse: + r"""Removes the attached IAM policies for a resource + + .. 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 metastore_v1beta + + async def sample_remove_iam_policy(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.RemoveIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.remove_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.RemoveIamPolicyRequest, dict]]): + The request object. Request message for + [DataprocMetastore.RemoveIamPolicy][google.cloud.metastore.v1beta.DataprocMetastore.RemoveIamPolicy]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.metastore_v1beta.types.RemoveIamPolicyResponse: + Response message for + [DataprocMetastore.RemoveIamPolicy][google.cloud.metastore.v1beta.DataprocMetastore.RemoveIamPolicy]. + + """ + # Create or coerce a protobuf request object. + request = metastore.RemoveIamPolicyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_iam_policy, + 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(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def query_metadata(self, + request: Optional[Union[metastore.QueryMetadataRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Query DPMS metadata. + + .. 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 metastore_v1beta + + async def sample_query_metadata(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.QueryMetadataRequest( + service="service_value", + query="query_value", + ) + + # Make the request + operation = client.query_metadata(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.QueryMetadataRequest, dict]]): + The request object. Request message for + [DataprocMetastore.QueryMetadata][google.cloud.metastore.v1beta.DataprocMetastore.QueryMetadata]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.metastore_v1beta.types.QueryMetadataResponse` Response message for + [DataprocMetastore.QueryMetadata][google.cloud.metastore.v1beta.DataprocMetastore.QueryMetadata]. + + """ + # Create or coerce a protobuf request object. + request = metastore.QueryMetadataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.query_metadata, + 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(( + ("service", request.service), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.QueryMetadataResponse, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def move_table_to_database(self, + request: Optional[Union[metastore.MoveTableToDatabaseRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Move a table to another database. + + .. 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 metastore_v1beta + + async def sample_move_table_to_database(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.MoveTableToDatabaseRequest( + service="service_value", + table_name="table_name_value", + db_name="db_name_value", + destination_db_name="destination_db_name_value", + ) + + # Make the request + operation = client.move_table_to_database(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.MoveTableToDatabaseRequest, dict]]): + The request object. Request message for + [DataprocMetastore.MoveTableToDatabase][google.cloud.metastore.v1beta.DataprocMetastore.MoveTableToDatabase]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.metastore_v1beta.types.MoveTableToDatabaseResponse` Response message for + [DataprocMetastore.MoveTableToDatabase][google.cloud.metastore.v1beta.DataprocMetastore.MoveTableToDatabase]. + + """ + # Create or coerce a protobuf request object. + request = metastore.MoveTableToDatabaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.move_table_to_database, + 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(( + ("service", request.service), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.MoveTableToDatabaseResponse, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def alter_metadata_resource_location(self, + request: Optional[Union[metastore.AlterMetadataResourceLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Alter metadata resource location. The metadata + resource can be a database, table, or partition. This + functionality only updates the parent directory for the + respective metadata resource and does not transfer any + existing data to the new 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 metastore_v1beta + + async def sample_alter_metadata_resource_location(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.AlterMetadataResourceLocationRequest( + service="service_value", + resource_name="resource_name_value", + location_uri="location_uri_value", + ) + + # Make the request + operation = client.alter_metadata_resource_location(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.AlterMetadataResourceLocationRequest, dict]]): + The request object. Request message for + [DataprocMetastore.AlterMetadataResourceLocation][google.cloud.metastore.v1beta.DataprocMetastore.AlterMetadataResourceLocation]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.metastore_v1beta.types.AlterMetadataResourceLocationResponse` Response message for + [DataprocMetastore.AlterMetadataResourceLocation][google.cloud.metastore.v1beta.DataprocMetastore.AlterMetadataResourceLocation]. + + """ + # Create or coerce a protobuf request object. + request = metastore.AlterMetadataResourceLocationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.alter_metadata_resource_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(( + ("service", request.service), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore.AlterMetadataResourceLocationResponse, + metadata_type=metastore.OperationMetadata, + ) + + # 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.set_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.GetIamPolicyRequest(**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_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.test_iam_permissions, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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): + 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__ = ( + "DataprocMetastoreAsyncClient", +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/client.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/client.py new file mode 100644 index 0000000..ff43ef7 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/client.py @@ -0,0 +1,3253 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.metastore_v1beta import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1beta.services.dataproc_metastore import pagers +from google.cloud.metastore_v1beta.types import metastore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DataprocMetastoreTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DataprocMetastoreGrpcTransport +from .transports.grpc_asyncio import DataprocMetastoreGrpcAsyncIOTransport +from .transports.rest import DataprocMetastoreRestTransport + + +class DataprocMetastoreClientMeta(type): + """Metaclass for the DataprocMetastore 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[DataprocMetastoreTransport]] + _transport_registry["grpc"] = DataprocMetastoreGrpcTransport + _transport_registry["grpc_asyncio"] = DataprocMetastoreGrpcAsyncIOTransport + _transport_registry["rest"] = DataprocMetastoreRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[DataprocMetastoreTransport]: + """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 DataprocMetastoreClient(metaclass=DataprocMetastoreClientMeta): + """Configures and manages metastore services. Metastore services are + fully managed, highly available, autoscaled, autohealing, OSS-native + deployments of technical metadata management software. Each + metastore service exposes a network endpoint through which metadata + queries are served. Metadata queries can originate from a variety of + sources, including Apache Hive, Apache Presto, and Apache Spark. + + The Dataproc Metastore API defines the following resource model: + + - The service works with a collection of Google Cloud projects, + named: ``/projects/*`` + + - Each project has a collection of available locations, named: + ``/locations/*`` (a location must refer to a Google Cloud + ``region``) + + - Each location has a collection of services, named: + ``/services/*`` + + - Dataproc Metastore services are resources with names of the form: + + ``/projects/{project_number}/locations/{location_id}/services/{service_id}``. + """ + + @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 = "metastore.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: + DataprocMetastoreClient: 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: + DataprocMetastoreClient: 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) -> DataprocMetastoreTransport: + """Returns the transport used by the client instance. + + Returns: + DataprocMetastoreTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def backup_path(project: str,location: str,service: str,backup: str,) -> str: + """Returns a fully-qualified backup string.""" + return "projects/{project}/locations/{location}/services/{service}/backups/{backup}".format(project=project, location=location, service=service, backup=backup, ) + + @staticmethod + def parse_backup_path(path: str) -> Dict[str,str]: + """Parses a backup path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/services/(?P.+?)/backups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def lake_path(project: str,location: str,lake: str,) -> str: + """Returns a fully-qualified lake string.""" + return "projects/{project}/locations/{location}/lakes/{lake}".format(project=project, location=location, lake=lake, ) + + @staticmethod + def parse_lake_path(path: str) -> Dict[str,str]: + """Parses a lake path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/lakes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def metadata_import_path(project: str,location: str,service: str,metadata_import: str,) -> str: + """Returns a fully-qualified metadata_import string.""" + return "projects/{project}/locations/{location}/services/{service}/metadataImports/{metadata_import}".format(project=project, location=location, service=service, metadata_import=metadata_import, ) + + @staticmethod + def parse_metadata_import_path(path: str) -> Dict[str,str]: + """Parses a metadata_import path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/services/(?P.+?)/metadataImports/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def network_path(project: str,network: str,) -> str: + """Returns a fully-qualified network string.""" + return "projects/{project}/global/networks/{network}".format(project=project, network=network, ) + + @staticmethod + def parse_network_path(path: str) -> Dict[str,str]: + """Parses a network path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/global/networks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_path(project: str,location: str,service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/services/{service}".format(project=project, location=location, service=service, ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str,str]: + """Parses a service path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/services/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def subnetwork_path(project: str,region: str,subnetwork: str,) -> str: + """Returns a fully-qualified subnetwork string.""" + return "projects/{project}/regions/{region}/subnetworks/{subnetwork}".format(project=project, region=region, subnetwork=subnetwork, ) + + @staticmethod + def parse_subnetwork_path(path: str) -> Dict[str,str]: + """Parses a subnetwork path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/regions/(?P.+?)/subnetworks/(?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, DataprocMetastoreTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dataproc metastore 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, DataprocMetastoreTransport]): 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, DataprocMetastoreTransport): + # transport is a DataprocMetastoreTransport 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_services(self, + request: Optional[Union[metastore.ListServicesRequest, 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.ListServicesPager: + r"""Lists services in a 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 metastore_v1beta + + def sample_list_services(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.ListServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.ListServicesRequest, dict]): + The request object. Request message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1beta.DataprocMetastore.ListServices]. + parent (str): + Required. The relative resource name of the location of + metastore services to list, in the following form: + + ``projects/{project_number}/locations/{location_id}``. + + 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.metastore_v1beta.services.dataproc_metastore.pagers.ListServicesPager: + Response message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1beta.DataprocMetastore.ListServices]. + + 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 metastore.ListServicesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.ListServicesRequest): + request = metastore.ListServicesRequest(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_services] + + # Certain 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.ListServicesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_service(self, + request: Optional[Union[metastore.GetServiceRequest, 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]] = (), + ) -> metastore.Service: + r"""Gets the details of a single service. + + .. 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 metastore_v1beta + + def sample_get_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.GetServiceRequest( + name="name_value", + ) + + # Make the request + response = client.get_service(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.GetServiceRequest, dict]): + The request object. Request message for + [DataprocMetastore.GetService][google.cloud.metastore.v1beta.DataprocMetastore.GetService]. + name (str): + Required. The relative resource name of the metastore + service to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + 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.metastore_v1beta.types.Service: + A managed metastore service that + serves metadata queries. + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 metastore.GetServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.GetServiceRequest): + request = metastore.GetServiceRequest(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_service] + + # Certain 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_service(self, + request: Optional[Union[metastore.CreateServiceRequest, dict]] = None, + *, + parent: Optional[str] = None, + service: Optional[metastore.Service] = None, + service_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a metastore service in a 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 metastore_v1beta + + def sample_create_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.CreateServiceRequest( + parent="parent_value", + service_id="service_id_value", + ) + + # Make the request + operation = client.create_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.CreateServiceRequest, dict]): + The request object. Request message for + [DataprocMetastore.CreateService][google.cloud.metastore.v1beta.DataprocMetastore.CreateService]. + parent (str): + Required. The relative resource name of the location in + which to create a metastore service, in the following + form: + + ``projects/{project_number}/locations/{location_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service (google.cloud.metastore_v1beta.types.Service): + Required. The Metastore service to create. The ``name`` + field is ignored. The ID of the created metastore + service must be provided in the request's ``service_id`` + field. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_id (str): + Required. The ID of the metastore + service, which is used as the final + component of the metastore service's + name. + This value must be between 2 and 63 + characters long inclusive, begin with a + letter, end with a letter or number, and + consist of alpha-numeric ASCII + characters or hyphens. + + This corresponds to the ``service_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1beta.types.Service` A + managed metastore service that serves metadata queries. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, service, service_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a metastore.CreateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.CreateServiceRequest): + request = metastore.CreateServiceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if service is not None: + request.service = service + if service_id is not None: + request.service_id = service_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.Service, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_service(self, + request: Optional[Union[metastore.UpdateServiceRequest, dict]] = None, + *, + service: Optional[metastore.Service] = 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]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single service. + + .. 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 metastore_v1beta + + def sample_update_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.UpdateServiceRequest( + ) + + # Make the request + operation = client.update_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.UpdateServiceRequest, dict]): + The request object. Request message for + [DataprocMetastore.UpdateService][google.cloud.metastore.v1beta.DataprocMetastore.UpdateService]. + service (google.cloud.metastore_v1beta.types.Service): + Required. The metastore service to update. The server + only merges fields in the service if they are specified + in ``update_mask``. + + The metastore service's ``name`` field is used to + identify the metastore service to be updated. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask used to specify the fields to be + overwritten in the metastore service resource by the + update. Fields specified in the ``update_mask`` are + relative to the resource (not to the full request). A + field is overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1beta.types.Service` A + managed metastore service that serves metadata queries. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, 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 metastore.UpdateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.UpdateServiceRequest): + request = metastore.UpdateServiceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if service is not None: + request.service = service + 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_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service.name", request.service.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.Service, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_service(self, + request: Optional[Union[metastore.DeleteServiceRequest, 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]] = (), + ) -> operation.Operation: + r"""Deletes a single service. + + .. 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 metastore_v1beta + + def sample_delete_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.DeleteServiceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.DeleteServiceRequest, dict]): + The request object. Request message for + [DataprocMetastore.DeleteService][google.cloud.metastore.v1beta.DataprocMetastore.DeleteService]. + name (str): + Required. The relative resource name of the metastore + service to delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 metastore.DeleteServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.DeleteServiceRequest): + request = metastore.DeleteServiceRequest(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_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_metadata_imports(self, + request: Optional[Union[metastore.ListMetadataImportsRequest, 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.ListMetadataImportsPager: + r"""Lists imports in a service. + + .. 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 metastore_v1beta + + def sample_list_metadata_imports(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.ListMetadataImportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_metadata_imports(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.ListMetadataImportsRequest, dict]): + The request object. Request message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1beta.DataprocMetastore.ListMetadataImports]. + parent (str): + Required. The relative resource name of the service + whose metadata imports to list, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports``. + + 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.metastore_v1beta.services.dataproc_metastore.pagers.ListMetadataImportsPager: + Response message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1beta.DataprocMetastore.ListMetadataImports]. + + 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 metastore.ListMetadataImportsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.ListMetadataImportsRequest): + request = metastore.ListMetadataImportsRequest(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_metadata_imports] + + # Certain 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.ListMetadataImportsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_metadata_import(self, + request: Optional[Union[metastore.GetMetadataImportRequest, 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]] = (), + ) -> metastore.MetadataImport: + r"""Gets details of a single import. + + .. 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 metastore_v1beta + + def sample_get_metadata_import(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.GetMetadataImportRequest( + name="name_value", + ) + + # Make the request + response = client.get_metadata_import(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.GetMetadataImportRequest, dict]): + The request object. Request message for + [DataprocMetastore.GetMetadataImport][google.cloud.metastore.v1beta.DataprocMetastore.GetMetadataImport]. + name (str): + Required. The relative resource name of the metadata + import to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports/{import_id}``. + + 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.metastore_v1beta.types.MetadataImport: + A metastore resource that imports + 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 metastore.GetMetadataImportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.GetMetadataImportRequest): + request = metastore.GetMetadataImportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_metadata_import] + + # Certain 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_metadata_import(self, + request: Optional[Union[metastore.CreateMetadataImportRequest, dict]] = None, + *, + parent: Optional[str] = None, + metadata_import: Optional[metastore.MetadataImport] = None, + metadata_import_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new MetadataImport 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 metastore_v1beta + + def sample_create_metadata_import(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.CreateMetadataImportRequest( + parent="parent_value", + metadata_import_id="metadata_import_id_value", + ) + + # Make the request + operation = client.create_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.CreateMetadataImportRequest, dict]): + The request object. Request message for + [DataprocMetastore.CreateMetadataImport][google.cloud.metastore.v1beta.DataprocMetastore.CreateMetadataImport]. + parent (str): + Required. The relative resource name of the service in + which to create a metastore import, in the following + form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + metadata_import (google.cloud.metastore_v1beta.types.MetadataImport): + Required. The metadata import to create. The ``name`` + field is ignored. The ID of the created metadata import + must be provided in the request's ``metadata_import_id`` + field. + + This corresponds to the ``metadata_import`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + metadata_import_id (str): + Required. The ID of the metadata + import, which is used as the final + component of the metadata import's name. + This value must be between 1 and 64 + characters long, begin with a letter, + end with a letter or number, and consist + of alpha-numeric ASCII characters or + hyphens. + + This corresponds to the ``metadata_import_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1beta.types.MetadataImport` + A metastore resource that imports 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([parent, metadata_import, metadata_import_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a metastore.CreateMetadataImportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.CreateMetadataImportRequest): + request = metastore.CreateMetadataImportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if metadata_import is not None: + request.metadata_import = metadata_import + if metadata_import_id is not None: + request.metadata_import_id = metadata_import_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_metadata_import] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.MetadataImport, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_metadata_import(self, + request: Optional[Union[metastore.UpdateMetadataImportRequest, dict]] = None, + *, + metadata_import: Optional[metastore.MetadataImport] = 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]] = (), + ) -> operation.Operation: + r"""Updates a single import. + Only the description field of MetadataImport is + supported to be updated. + + .. 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 metastore_v1beta + + def sample_update_metadata_import(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.UpdateMetadataImportRequest( + ) + + # Make the request + operation = client.update_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.UpdateMetadataImportRequest, dict]): + The request object. Request message for + [DataprocMetastore.UpdateMetadataImport][google.cloud.metastore.v1beta.DataprocMetastore.UpdateMetadataImport]. + metadata_import (google.cloud.metastore_v1beta.types.MetadataImport): + Required. The metadata import to update. The server only + merges fields in the import if they are specified in + ``update_mask``. + + The metadata import's ``name`` field is used to identify + the metastore import to be updated. + + This corresponds to the ``metadata_import`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask used to specify the fields to be + overwritten in the metadata import resource by the + update. Fields specified in the ``update_mask`` are + relative to the resource (not to the full request). A + field is overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1beta.types.MetadataImport` + A metastore resource that imports 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([metadata_import, 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 metastore.UpdateMetadataImportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.UpdateMetadataImportRequest): + request = metastore.UpdateMetadataImportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if metadata_import is not None: + request.metadata_import = metadata_import + 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_metadata_import] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("metadata_import.name", request.metadata_import.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.MetadataImport, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def export_metadata(self, + request: Optional[Union[metastore.ExportMetadataRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports metadata from a service. + + .. 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 metastore_v1beta + + def sample_export_metadata(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.ExportMetadataRequest( + destination_gcs_folder="destination_gcs_folder_value", + service="service_value", + ) + + # Make the request + operation = client.export_metadata(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.ExportMetadataRequest, dict]): + The request object. Request message for + [DataprocMetastore.ExportMetadata][google.cloud.metastore.v1beta.DataprocMetastore.ExportMetadata]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1beta.types.MetadataExport` + The details of a metadata export operation. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a metastore.ExportMetadataRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.ExportMetadataRequest): + request = metastore.ExportMetadataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_metadata] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service", request.service), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.MetadataExport, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def restore_service(self, + request: Optional[Union[metastore.RestoreServiceRequest, dict]] = None, + *, + service: Optional[str] = None, + backup: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Restores a service from a backup. + + .. 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 metastore_v1beta + + def sample_restore_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.RestoreServiceRequest( + service="service_value", + backup="backup_value", + ) + + # Make the request + operation = client.restore_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.RestoreServiceRequest, dict]): + The request object. Request message for [DataprocMetastore.Restore][]. + service (str): + Required. The relative resource name of the metastore + service to run restore, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup (str): + Required. The relative resource name of the metastore + service backup to restore from, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1beta.types.Restore` The + details of a metadata restore operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, backup]) + if request is 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 metastore.RestoreServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.RestoreServiceRequest): + request = metastore.RestoreServiceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if service is not None: + request.service = service + if backup is not None: + request.backup = backup + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.restore_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service", request.service), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.Restore, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_backups(self, + request: Optional[Union[metastore.ListBackupsRequest, 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.ListBackupsPager: + r"""Lists backups in a service. + + .. 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 metastore_v1beta + + def sample_list_backups(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.ListBackupsRequest, dict]): + The request object. Request message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1beta.DataprocMetastore.ListBackups]. + parent (str): + Required. The relative resource name of the service + whose backups to list, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups``. + + 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.metastore_v1beta.services.dataproc_metastore.pagers.ListBackupsPager: + Response message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1beta.DataprocMetastore.ListBackups]. + + 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 metastore.ListBackupsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.ListBackupsRequest): + request = metastore.ListBackupsRequest(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_backups] + + # Certain 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.ListBackupsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_backup(self, + request: Optional[Union[metastore.GetBackupRequest, 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]] = (), + ) -> metastore.Backup: + r"""Gets details of a single backup. + + .. 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 metastore_v1beta + + def sample_get_backup(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.GetBackupRequest, dict]): + The request object. Request message for + [DataprocMetastore.GetBackup][google.cloud.metastore.v1beta.DataprocMetastore.GetBackup]. + name (str): + Required. The relative resource name of the backup to + retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + + 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.metastore_v1beta.types.Backup: + The details of a backup resource. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a metastore.GetBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.GetBackupRequest): + request = metastore.GetBackupRequest(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_backup] + + # Certain 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_backup(self, + request: Optional[Union[metastore.CreateBackupRequest, dict]] = None, + *, + parent: Optional[str] = None, + backup: Optional[metastore.Backup] = None, + backup_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new backup 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 metastore_v1beta + + def sample_create_backup(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + ) + + # Make the request + operation = client.create_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.CreateBackupRequest, dict]): + The request object. Request message for + [DataprocMetastore.CreateBackup][google.cloud.metastore.v1beta.DataprocMetastore.CreateBackup]. + parent (str): + Required. The relative resource name of the service in + which to create a backup of the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup (google.cloud.metastore_v1beta.types.Backup): + Required. The backup to create. The ``name`` field is + ignored. The ID of the created backup must be provided + in the request's ``backup_id`` field. + + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_id (str): + Required. The ID of the backup, which + is used as the final component of the + backup's name. + This value must be between 1 and 64 + characters long, begin with a letter, + end with a letter or number, and consist + of alpha-numeric ASCII characters or + hyphens. + + This corresponds to the ``backup_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1beta.types.Backup` The + details of a backup resource. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, backup, backup_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a metastore.CreateBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.CreateBackupRequest): + request = metastore.CreateBackupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if backup is not None: + request.backup = backup + if backup_id is not None: + request.backup_id = backup_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_backup] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.Backup, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_backup(self, + request: Optional[Union[metastore.DeleteBackupRequest, 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]] = (), + ) -> operation.Operation: + r"""Deletes a single backup. + + .. 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 metastore_v1beta + + def sample_delete_backup(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.DeleteBackupRequest, dict]): + The request object. Request message for + [DataprocMetastore.DeleteBackup][google.cloud.metastore.v1beta.DataprocMetastore.DeleteBackup]. + name (str): + Required. The relative resource name of the backup to + delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 metastore.DeleteBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.DeleteBackupRequest): + request = metastore.DeleteBackupRequest(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_backup] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def remove_iam_policy(self, + request: Optional[Union[metastore.RemoveIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> metastore.RemoveIamPolicyResponse: + r"""Removes the attached IAM policies for a resource + + .. 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 metastore_v1beta + + def sample_remove_iam_policy(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.RemoveIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.remove_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.RemoveIamPolicyRequest, dict]): + The request object. Request message for + [DataprocMetastore.RemoveIamPolicy][google.cloud.metastore.v1beta.DataprocMetastore.RemoveIamPolicy]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.metastore_v1beta.types.RemoveIamPolicyResponse: + Response message for + [DataprocMetastore.RemoveIamPolicy][google.cloud.metastore.v1beta.DataprocMetastore.RemoveIamPolicy]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a metastore.RemoveIamPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.RemoveIamPolicyRequest): + request = metastore.RemoveIamPolicyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def query_metadata(self, + request: Optional[Union[metastore.QueryMetadataRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Query DPMS metadata. + + .. 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 metastore_v1beta + + def sample_query_metadata(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.QueryMetadataRequest( + service="service_value", + query="query_value", + ) + + # Make the request + operation = client.query_metadata(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.QueryMetadataRequest, dict]): + The request object. Request message for + [DataprocMetastore.QueryMetadata][google.cloud.metastore.v1beta.DataprocMetastore.QueryMetadata]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.metastore_v1beta.types.QueryMetadataResponse` Response message for + [DataprocMetastore.QueryMetadata][google.cloud.metastore.v1beta.DataprocMetastore.QueryMetadata]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a metastore.QueryMetadataRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.QueryMetadataRequest): + request = metastore.QueryMetadataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.query_metadata] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service", request.service), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.QueryMetadataResponse, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def move_table_to_database(self, + request: Optional[Union[metastore.MoveTableToDatabaseRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Move a table to another database. + + .. 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 metastore_v1beta + + def sample_move_table_to_database(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.MoveTableToDatabaseRequest( + service="service_value", + table_name="table_name_value", + db_name="db_name_value", + destination_db_name="destination_db_name_value", + ) + + # Make the request + operation = client.move_table_to_database(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.MoveTableToDatabaseRequest, dict]): + The request object. Request message for + [DataprocMetastore.MoveTableToDatabase][google.cloud.metastore.v1beta.DataprocMetastore.MoveTableToDatabase]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.metastore_v1beta.types.MoveTableToDatabaseResponse` Response message for + [DataprocMetastore.MoveTableToDatabase][google.cloud.metastore.v1beta.DataprocMetastore.MoveTableToDatabase]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a metastore.MoveTableToDatabaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.MoveTableToDatabaseRequest): + request = metastore.MoveTableToDatabaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.move_table_to_database] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service", request.service), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.MoveTableToDatabaseResponse, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def alter_metadata_resource_location(self, + request: Optional[Union[metastore.AlterMetadataResourceLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Alter metadata resource location. The metadata + resource can be a database, table, or partition. This + functionality only updates the parent directory for the + respective metadata resource and does not transfer any + existing data to the new 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 metastore_v1beta + + def sample_alter_metadata_resource_location(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.AlterMetadataResourceLocationRequest( + service="service_value", + resource_name="resource_name_value", + location_uri="location_uri_value", + ) + + # Make the request + operation = client.alter_metadata_resource_location(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.AlterMetadataResourceLocationRequest, dict]): + The request object. Request message for + [DataprocMetastore.AlterMetadataResourceLocation][google.cloud.metastore.v1beta.DataprocMetastore.AlterMetadataResourceLocation]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.metastore_v1beta.types.AlterMetadataResourceLocationResponse` Response message for + [DataprocMetastore.AlterMetadataResourceLocation][google.cloud.metastore.v1beta.DataprocMetastore.AlterMetadataResourceLocation]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a metastore.AlterMetadataResourceLocationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore.AlterMetadataResourceLocationRequest): + request = metastore.AlterMetadataResourceLocationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.alter_metadata_resource_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service", request.service), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore.AlterMetadataResourceLocationResponse, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "DataprocMetastoreClient": + 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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__ = ( + "DataprocMetastoreClient", +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/pagers.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/pagers.py new file mode 100644 index 0000000..3676070 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/pagers.py @@ -0,0 +1,381 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.metastore_v1beta.types import metastore + + +class ListServicesPager: + """A pager for iterating through ``list_services`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1beta.types.ListServicesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``services`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServices`` requests and continue to iterate + through the ``services`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1beta.types.ListServicesResponse` + 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[..., metastore.ListServicesResponse], + request: metastore.ListServicesRequest, + response: metastore.ListServicesResponse, + *, + 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.metastore_v1beta.types.ListServicesRequest): + The initial request object. + response (google.cloud.metastore_v1beta.types.ListServicesResponse): + 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 = metastore.ListServicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[metastore.ListServicesResponse]: + 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[metastore.Service]: + for page in self.pages: + yield from page.services + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServicesAsyncPager: + """A pager for iterating through ``list_services`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1beta.types.ListServicesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``services`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServices`` requests and continue to iterate + through the ``services`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1beta.types.ListServicesResponse` + 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[metastore.ListServicesResponse]], + request: metastore.ListServicesRequest, + response: metastore.ListServicesResponse, + *, + 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.metastore_v1beta.types.ListServicesRequest): + The initial request object. + response (google.cloud.metastore_v1beta.types.ListServicesResponse): + 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 = metastore.ListServicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[metastore.ListServicesResponse]: + 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[metastore.Service]: + async def async_generator(): + async for page in self.pages: + for response in page.services: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMetadataImportsPager: + """A pager for iterating through ``list_metadata_imports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1beta.types.ListMetadataImportsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``metadata_imports`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMetadataImports`` requests and continue to iterate + through the ``metadata_imports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1beta.types.ListMetadataImportsResponse` + 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[..., metastore.ListMetadataImportsResponse], + request: metastore.ListMetadataImportsRequest, + response: metastore.ListMetadataImportsResponse, + *, + 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.metastore_v1beta.types.ListMetadataImportsRequest): + The initial request object. + response (google.cloud.metastore_v1beta.types.ListMetadataImportsResponse): + 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 = metastore.ListMetadataImportsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[metastore.ListMetadataImportsResponse]: + 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[metastore.MetadataImport]: + for page in self.pages: + yield from page.metadata_imports + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMetadataImportsAsyncPager: + """A pager for iterating through ``list_metadata_imports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1beta.types.ListMetadataImportsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``metadata_imports`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMetadataImports`` requests and continue to iterate + through the ``metadata_imports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1beta.types.ListMetadataImportsResponse` + 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[metastore.ListMetadataImportsResponse]], + request: metastore.ListMetadataImportsRequest, + response: metastore.ListMetadataImportsResponse, + *, + 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.metastore_v1beta.types.ListMetadataImportsRequest): + The initial request object. + response (google.cloud.metastore_v1beta.types.ListMetadataImportsResponse): + 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 = metastore.ListMetadataImportsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[metastore.ListMetadataImportsResponse]: + 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[metastore.MetadataImport]: + async def async_generator(): + async for page in self.pages: + for response in page.metadata_imports: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBackupsPager: + """A pager for iterating through ``list_backups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1beta.types.ListBackupsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``backups`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBackups`` requests and continue to iterate + through the ``backups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1beta.types.ListBackupsResponse` + 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[..., metastore.ListBackupsResponse], + request: metastore.ListBackupsRequest, + response: metastore.ListBackupsResponse, + *, + 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.metastore_v1beta.types.ListBackupsRequest): + The initial request object. + response (google.cloud.metastore_v1beta.types.ListBackupsResponse): + 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 = metastore.ListBackupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[metastore.ListBackupsResponse]: + 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[metastore.Backup]: + for page in self.pages: + yield from page.backups + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBackupsAsyncPager: + """A pager for iterating through ``list_backups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1beta.types.ListBackupsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``backups`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBackups`` requests and continue to iterate + through the ``backups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1beta.types.ListBackupsResponse` + 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[metastore.ListBackupsResponse]], + request: metastore.ListBackupsRequest, + response: metastore.ListBackupsResponse, + *, + 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.metastore_v1beta.types.ListBackupsRequest): + The initial request object. + response (google.cloud.metastore_v1beta.types.ListBackupsResponse): + 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 = metastore.ListBackupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[metastore.ListBackupsResponse]: + 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[metastore.Backup]: + async def async_generator(): + async for page in self.pages: + for response in page.backups: + 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/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/__init__.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/__init__.py new file mode 100644 index 0000000..38e3513 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import DataprocMetastoreTransport +from .grpc import DataprocMetastoreGrpcTransport +from .grpc_asyncio import DataprocMetastoreGrpcAsyncIOTransport +from .rest import DataprocMetastoreRestTransport +from .rest import DataprocMetastoreRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DataprocMetastoreTransport]] +_transport_registry['grpc'] = DataprocMetastoreGrpcTransport +_transport_registry['grpc_asyncio'] = DataprocMetastoreGrpcAsyncIOTransport +_transport_registry['rest'] = DataprocMetastoreRestTransport + +__all__ = ( + 'DataprocMetastoreTransport', + 'DataprocMetastoreGrpcTransport', + 'DataprocMetastoreGrpcAsyncIOTransport', + 'DataprocMetastoreRestTransport', + 'DataprocMetastoreRestInterceptor', +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/base.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/base.py new file mode 100644 index 0000000..497dcf6 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/base.py @@ -0,0 +1,484 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.metastore_v1beta import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1beta.types import metastore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class DataprocMetastoreTransport(abc.ABC): + """Abstract transport class for DataprocMetastore.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'metastore.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_services: gapic_v1.method.wrap_method( + self.list_services, + default_timeout=None, + client_info=client_info, + ), + self.get_service: gapic_v1.method.wrap_method( + self.get_service, + default_timeout=None, + client_info=client_info, + ), + self.create_service: gapic_v1.method.wrap_method( + self.create_service, + default_timeout=60.0, + client_info=client_info, + ), + self.update_service: gapic_v1.method.wrap_method( + self.update_service, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_service: gapic_v1.method.wrap_method( + self.delete_service, + default_timeout=60.0, + client_info=client_info, + ), + self.list_metadata_imports: gapic_v1.method.wrap_method( + self.list_metadata_imports, + default_timeout=None, + client_info=client_info, + ), + self.get_metadata_import: gapic_v1.method.wrap_method( + self.get_metadata_import, + default_timeout=None, + client_info=client_info, + ), + self.create_metadata_import: gapic_v1.method.wrap_method( + self.create_metadata_import, + default_timeout=60.0, + client_info=client_info, + ), + self.update_metadata_import: gapic_v1.method.wrap_method( + self.update_metadata_import, + default_timeout=60.0, + client_info=client_info, + ), + self.export_metadata: gapic_v1.method.wrap_method( + self.export_metadata, + default_timeout=60.0, + client_info=client_info, + ), + self.restore_service: gapic_v1.method.wrap_method( + self.restore_service, + default_timeout=60.0, + client_info=client_info, + ), + self.list_backups: gapic_v1.method.wrap_method( + self.list_backups, + default_timeout=None, + client_info=client_info, + ), + self.get_backup: gapic_v1.method.wrap_method( + self.get_backup, + default_timeout=None, + client_info=client_info, + ), + self.create_backup: gapic_v1.method.wrap_method( + self.create_backup, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_backup: gapic_v1.method.wrap_method( + self.delete_backup, + default_timeout=60.0, + client_info=client_info, + ), + self.remove_iam_policy: gapic_v1.method.wrap_method( + self.remove_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.query_metadata: gapic_v1.method.wrap_method( + self.query_metadata, + default_timeout=None, + client_info=client_info, + ), + self.move_table_to_database: gapic_v1.method.wrap_method( + self.move_table_to_database, + default_timeout=None, + client_info=client_info, + ), + self.alter_metadata_resource_location: gapic_v1.method.wrap_method( + self.alter_metadata_resource_location, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_services(self) -> Callable[ + [metastore.ListServicesRequest], + Union[ + metastore.ListServicesResponse, + Awaitable[metastore.ListServicesResponse] + ]]: + raise NotImplementedError() + + @property + def get_service(self) -> Callable[ + [metastore.GetServiceRequest], + Union[ + metastore.Service, + Awaitable[metastore.Service] + ]]: + raise NotImplementedError() + + @property + def create_service(self) -> Callable[ + [metastore.CreateServiceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_service(self) -> Callable[ + [metastore.UpdateServiceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_service(self) -> Callable[ + [metastore.DeleteServiceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_metadata_imports(self) -> Callable[ + [metastore.ListMetadataImportsRequest], + Union[ + metastore.ListMetadataImportsResponse, + Awaitable[metastore.ListMetadataImportsResponse] + ]]: + raise NotImplementedError() + + @property + def get_metadata_import(self) -> Callable[ + [metastore.GetMetadataImportRequest], + Union[ + metastore.MetadataImport, + Awaitable[metastore.MetadataImport] + ]]: + raise NotImplementedError() + + @property + def create_metadata_import(self) -> Callable[ + [metastore.CreateMetadataImportRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_metadata_import(self) -> Callable[ + [metastore.UpdateMetadataImportRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def export_metadata(self) -> Callable[ + [metastore.ExportMetadataRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def restore_service(self) -> Callable[ + [metastore.RestoreServiceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_backups(self) -> Callable[ + [metastore.ListBackupsRequest], + Union[ + metastore.ListBackupsResponse, + Awaitable[metastore.ListBackupsResponse] + ]]: + raise NotImplementedError() + + @property + def get_backup(self) -> Callable[ + [metastore.GetBackupRequest], + Union[ + metastore.Backup, + Awaitable[metastore.Backup] + ]]: + raise NotImplementedError() + + @property + def create_backup(self) -> Callable[ + [metastore.CreateBackupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_backup(self) -> Callable[ + [metastore.DeleteBackupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_iam_policy(self) -> Callable[ + [metastore.RemoveIamPolicyRequest], + Union[ + metastore.RemoveIamPolicyResponse, + Awaitable[metastore.RemoveIamPolicyResponse] + ]]: + raise NotImplementedError() + + @property + def query_metadata(self) -> Callable[ + [metastore.QueryMetadataRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def move_table_to_database(self) -> Callable[ + [metastore.MoveTableToDatabaseRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def alter_metadata_resource_location(self) -> Callable[ + [metastore.AlterMetadataResourceLocationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + 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 delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + 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__ = ( + 'DataprocMetastoreTransport', +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/grpc.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/grpc.py new file mode 100644 index 0000000..81b090f --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/grpc.py @@ -0,0 +1,954 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1beta.types import metastore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from .base import DataprocMetastoreTransport, DEFAULT_CLIENT_INFO + + +class DataprocMetastoreGrpcTransport(DataprocMetastoreTransport): + """gRPC backend transport for DataprocMetastore. + + Configures and manages metastore services. Metastore services are + fully managed, highly available, autoscaled, autohealing, OSS-native + deployments of technical metadata management software. Each + metastore service exposes a network endpoint through which metadata + queries are served. Metadata queries can originate from a variety of + sources, including Apache Hive, Apache Presto, and Apache Spark. + + The Dataproc Metastore API defines the following resource model: + + - The service works with a collection of Google Cloud projects, + named: ``/projects/*`` + + - Each project has a collection of available locations, named: + ``/locations/*`` (a location must refer to a Google Cloud + ``region``) + + - Each location has a collection of services, named: + ``/services/*`` + + - Dataproc Metastore services are resources with names of the form: + + ``/projects/{project_number}/locations/{location_id}/services/{service_id}``. + + 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 = 'metastore.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] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + 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 = 'metastore.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 operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_services(self) -> Callable[ + [metastore.ListServicesRequest], + metastore.ListServicesResponse]: + r"""Return a callable for the list services method over gRPC. + + Lists services in a project and location. + + Returns: + Callable[[~.ListServicesRequest], + ~.ListServicesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_services' not in self._stubs: + self._stubs['list_services'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/ListServices', + request_serializer=metastore.ListServicesRequest.serialize, + response_deserializer=metastore.ListServicesResponse.deserialize, + ) + return self._stubs['list_services'] + + @property + def get_service(self) -> Callable[ + [metastore.GetServiceRequest], + metastore.Service]: + r"""Return a callable for the get service method over gRPC. + + Gets the details of a single service. + + Returns: + Callable[[~.GetServiceRequest], + ~.Service]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_service' not in self._stubs: + self._stubs['get_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/GetService', + request_serializer=metastore.GetServiceRequest.serialize, + response_deserializer=metastore.Service.deserialize, + ) + return self._stubs['get_service'] + + @property + def create_service(self) -> Callable[ + [metastore.CreateServiceRequest], + operations_pb2.Operation]: + r"""Return a callable for the create service method over gRPC. + + Creates a metastore service in a project and + location. + + Returns: + Callable[[~.CreateServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_service' not in self._stubs: + self._stubs['create_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/CreateService', + request_serializer=metastore.CreateServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_service'] + + @property + def update_service(self) -> Callable[ + [metastore.UpdateServiceRequest], + operations_pb2.Operation]: + r"""Return a callable for the update service method over gRPC. + + Updates the parameters of a single service. + + Returns: + Callable[[~.UpdateServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_service' not in self._stubs: + self._stubs['update_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/UpdateService', + request_serializer=metastore.UpdateServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_service'] + + @property + def delete_service(self) -> Callable[ + [metastore.DeleteServiceRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete service method over gRPC. + + Deletes a single service. + + Returns: + Callable[[~.DeleteServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_service' not in self._stubs: + self._stubs['delete_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/DeleteService', + request_serializer=metastore.DeleteServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_service'] + + @property + def list_metadata_imports(self) -> Callable[ + [metastore.ListMetadataImportsRequest], + metastore.ListMetadataImportsResponse]: + r"""Return a callable for the list metadata imports method over gRPC. + + Lists imports in a service. + + Returns: + Callable[[~.ListMetadataImportsRequest], + ~.ListMetadataImportsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_metadata_imports' not in self._stubs: + self._stubs['list_metadata_imports'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/ListMetadataImports', + request_serializer=metastore.ListMetadataImportsRequest.serialize, + response_deserializer=metastore.ListMetadataImportsResponse.deserialize, + ) + return self._stubs['list_metadata_imports'] + + @property + def get_metadata_import(self) -> Callable[ + [metastore.GetMetadataImportRequest], + metastore.MetadataImport]: + r"""Return a callable for the get metadata import method over gRPC. + + Gets details of a single import. + + Returns: + Callable[[~.GetMetadataImportRequest], + ~.MetadataImport]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_metadata_import' not in self._stubs: + self._stubs['get_metadata_import'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/GetMetadataImport', + request_serializer=metastore.GetMetadataImportRequest.serialize, + response_deserializer=metastore.MetadataImport.deserialize, + ) + return self._stubs['get_metadata_import'] + + @property + def create_metadata_import(self) -> Callable[ + [metastore.CreateMetadataImportRequest], + operations_pb2.Operation]: + r"""Return a callable for the create metadata import method over gRPC. + + Creates a new MetadataImport in a given project and + location. + + Returns: + Callable[[~.CreateMetadataImportRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_metadata_import' not in self._stubs: + self._stubs['create_metadata_import'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/CreateMetadataImport', + request_serializer=metastore.CreateMetadataImportRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_metadata_import'] + + @property + def update_metadata_import(self) -> Callable[ + [metastore.UpdateMetadataImportRequest], + operations_pb2.Operation]: + r"""Return a callable for the update metadata import method over gRPC. + + Updates a single import. + Only the description field of MetadataImport is + supported to be updated. + + Returns: + Callable[[~.UpdateMetadataImportRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_metadata_import' not in self._stubs: + self._stubs['update_metadata_import'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/UpdateMetadataImport', + request_serializer=metastore.UpdateMetadataImportRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_metadata_import'] + + @property + def export_metadata(self) -> Callable[ + [metastore.ExportMetadataRequest], + operations_pb2.Operation]: + r"""Return a callable for the export metadata method over gRPC. + + Exports metadata from a service. + + Returns: + Callable[[~.ExportMetadataRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_metadata' not in self._stubs: + self._stubs['export_metadata'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/ExportMetadata', + request_serializer=metastore.ExportMetadataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_metadata'] + + @property + def restore_service(self) -> Callable[ + [metastore.RestoreServiceRequest], + operations_pb2.Operation]: + r"""Return a callable for the restore service method over gRPC. + + Restores a service from a backup. + + Returns: + Callable[[~.RestoreServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'restore_service' not in self._stubs: + self._stubs['restore_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/RestoreService', + request_serializer=metastore.RestoreServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_service'] + + @property + def list_backups(self) -> Callable[ + [metastore.ListBackupsRequest], + metastore.ListBackupsResponse]: + r"""Return a callable for the list backups method over gRPC. + + Lists backups in a service. + + Returns: + Callable[[~.ListBackupsRequest], + ~.ListBackupsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_backups' not in self._stubs: + self._stubs['list_backups'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/ListBackups', + request_serializer=metastore.ListBackupsRequest.serialize, + response_deserializer=metastore.ListBackupsResponse.deserialize, + ) + return self._stubs['list_backups'] + + @property + def get_backup(self) -> Callable[ + [metastore.GetBackupRequest], + metastore.Backup]: + r"""Return a callable for the get backup method over gRPC. + + Gets details of a single backup. + + Returns: + Callable[[~.GetBackupRequest], + ~.Backup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_backup' not in self._stubs: + self._stubs['get_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/GetBackup', + request_serializer=metastore.GetBackupRequest.serialize, + response_deserializer=metastore.Backup.deserialize, + ) + return self._stubs['get_backup'] + + @property + def create_backup(self) -> Callable[ + [metastore.CreateBackupRequest], + operations_pb2.Operation]: + r"""Return a callable for the create backup method over gRPC. + + Creates a new backup in a given project and location. + + Returns: + Callable[[~.CreateBackupRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_backup' not in self._stubs: + self._stubs['create_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/CreateBackup', + request_serializer=metastore.CreateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_backup'] + + @property + def delete_backup(self) -> Callable[ + [metastore.DeleteBackupRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete backup method over gRPC. + + Deletes a single backup. + + Returns: + Callable[[~.DeleteBackupRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_backup' not in self._stubs: + self._stubs['delete_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/DeleteBackup', + request_serializer=metastore.DeleteBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_backup'] + + @property + def remove_iam_policy(self) -> Callable[ + [metastore.RemoveIamPolicyRequest], + metastore.RemoveIamPolicyResponse]: + r"""Return a callable for the remove iam policy method over gRPC. + + Removes the attached IAM policies for a resource + + Returns: + Callable[[~.RemoveIamPolicyRequest], + ~.RemoveIamPolicyResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_iam_policy' not in self._stubs: + self._stubs['remove_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/RemoveIamPolicy', + request_serializer=metastore.RemoveIamPolicyRequest.serialize, + response_deserializer=metastore.RemoveIamPolicyResponse.deserialize, + ) + return self._stubs['remove_iam_policy'] + + @property + def query_metadata(self) -> Callable[ + [metastore.QueryMetadataRequest], + operations_pb2.Operation]: + r"""Return a callable for the query metadata method over gRPC. + + Query DPMS metadata. + + Returns: + Callable[[~.QueryMetadataRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'query_metadata' not in self._stubs: + self._stubs['query_metadata'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/QueryMetadata', + request_serializer=metastore.QueryMetadataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['query_metadata'] + + @property + def move_table_to_database(self) -> Callable[ + [metastore.MoveTableToDatabaseRequest], + operations_pb2.Operation]: + r"""Return a callable for the move table to database method over gRPC. + + Move a table to another database. + + Returns: + Callable[[~.MoveTableToDatabaseRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'move_table_to_database' not in self._stubs: + self._stubs['move_table_to_database'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/MoveTableToDatabase', + request_serializer=metastore.MoveTableToDatabaseRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['move_table_to_database'] + + @property + def alter_metadata_resource_location(self) -> Callable[ + [metastore.AlterMetadataResourceLocationRequest], + operations_pb2.Operation]: + r"""Return a callable for the alter metadata resource + location method over gRPC. + + Alter metadata resource location. The metadata + resource can be a database, table, or partition. This + functionality only updates the parent directory for the + respective metadata resource and does not transfer any + existing data to the new location. + + Returns: + Callable[[~.AlterMetadataResourceLocationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'alter_metadata_resource_location' not in self._stubs: + self._stubs['alter_metadata_resource_location'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/AlterMetadataResourceLocation', + request_serializer=metastore.AlterMetadataResourceLocationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['alter_metadata_resource_location'] + + 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 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 set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'DataprocMetastoreGrpcTransport', +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/grpc_asyncio.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/grpc_asyncio.py new file mode 100644 index 0000000..73bcf5f --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/grpc_asyncio.py @@ -0,0 +1,953 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1beta.types import metastore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from .base import DataprocMetastoreTransport, DEFAULT_CLIENT_INFO +from .grpc import DataprocMetastoreGrpcTransport + + +class DataprocMetastoreGrpcAsyncIOTransport(DataprocMetastoreTransport): + """gRPC AsyncIO backend transport for DataprocMetastore. + + Configures and manages metastore services. Metastore services are + fully managed, highly available, autoscaled, autohealing, OSS-native + deployments of technical metadata management software. Each + metastore service exposes a network endpoint through which metadata + queries are served. Metadata queries can originate from a variety of + sources, including Apache Hive, Apache Presto, and Apache Spark. + + The Dataproc Metastore API defines the following resource model: + + - The service works with a collection of Google Cloud projects, + named: ``/projects/*`` + + - Each project has a collection of available locations, named: + ``/locations/*`` (a location must refer to a Google Cloud + ``region``) + + - Each location has a collection of services, named: + ``/services/*`` + + - Dataproc Metastore services are resources with names of the form: + + ``/projects/{project_number}/locations/{location_id}/services/{service_id}``. + + 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 = 'metastore.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 = 'metastore.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] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + 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 operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_services(self) -> Callable[ + [metastore.ListServicesRequest], + Awaitable[metastore.ListServicesResponse]]: + r"""Return a callable for the list services method over gRPC. + + Lists services in a project and location. + + Returns: + Callable[[~.ListServicesRequest], + Awaitable[~.ListServicesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_services' not in self._stubs: + self._stubs['list_services'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/ListServices', + request_serializer=metastore.ListServicesRequest.serialize, + response_deserializer=metastore.ListServicesResponse.deserialize, + ) + return self._stubs['list_services'] + + @property + def get_service(self) -> Callable[ + [metastore.GetServiceRequest], + Awaitable[metastore.Service]]: + r"""Return a callable for the get service method over gRPC. + + Gets the details of a single service. + + Returns: + Callable[[~.GetServiceRequest], + Awaitable[~.Service]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_service' not in self._stubs: + self._stubs['get_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/GetService', + request_serializer=metastore.GetServiceRequest.serialize, + response_deserializer=metastore.Service.deserialize, + ) + return self._stubs['get_service'] + + @property + def create_service(self) -> Callable[ + [metastore.CreateServiceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create service method over gRPC. + + Creates a metastore service in a project and + location. + + Returns: + Callable[[~.CreateServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_service' not in self._stubs: + self._stubs['create_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/CreateService', + request_serializer=metastore.CreateServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_service'] + + @property + def update_service(self) -> Callable[ + [metastore.UpdateServiceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update service method over gRPC. + + Updates the parameters of a single service. + + Returns: + Callable[[~.UpdateServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_service' not in self._stubs: + self._stubs['update_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/UpdateService', + request_serializer=metastore.UpdateServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_service'] + + @property + def delete_service(self) -> Callable[ + [metastore.DeleteServiceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete service method over gRPC. + + Deletes a single service. + + Returns: + Callable[[~.DeleteServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_service' not in self._stubs: + self._stubs['delete_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/DeleteService', + request_serializer=metastore.DeleteServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_service'] + + @property + def list_metadata_imports(self) -> Callable[ + [metastore.ListMetadataImportsRequest], + Awaitable[metastore.ListMetadataImportsResponse]]: + r"""Return a callable for the list metadata imports method over gRPC. + + Lists imports in a service. + + Returns: + Callable[[~.ListMetadataImportsRequest], + Awaitable[~.ListMetadataImportsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_metadata_imports' not in self._stubs: + self._stubs['list_metadata_imports'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/ListMetadataImports', + request_serializer=metastore.ListMetadataImportsRequest.serialize, + response_deserializer=metastore.ListMetadataImportsResponse.deserialize, + ) + return self._stubs['list_metadata_imports'] + + @property + def get_metadata_import(self) -> Callable[ + [metastore.GetMetadataImportRequest], + Awaitable[metastore.MetadataImport]]: + r"""Return a callable for the get metadata import method over gRPC. + + Gets details of a single import. + + Returns: + Callable[[~.GetMetadataImportRequest], + Awaitable[~.MetadataImport]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_metadata_import' not in self._stubs: + self._stubs['get_metadata_import'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/GetMetadataImport', + request_serializer=metastore.GetMetadataImportRequest.serialize, + response_deserializer=metastore.MetadataImport.deserialize, + ) + return self._stubs['get_metadata_import'] + + @property + def create_metadata_import(self) -> Callable[ + [metastore.CreateMetadataImportRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create metadata import method over gRPC. + + Creates a new MetadataImport in a given project and + location. + + Returns: + Callable[[~.CreateMetadataImportRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_metadata_import' not in self._stubs: + self._stubs['create_metadata_import'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/CreateMetadataImport', + request_serializer=metastore.CreateMetadataImportRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_metadata_import'] + + @property + def update_metadata_import(self) -> Callable[ + [metastore.UpdateMetadataImportRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update metadata import method over gRPC. + + Updates a single import. + Only the description field of MetadataImport is + supported to be updated. + + Returns: + Callable[[~.UpdateMetadataImportRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_metadata_import' not in self._stubs: + self._stubs['update_metadata_import'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/UpdateMetadataImport', + request_serializer=metastore.UpdateMetadataImportRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_metadata_import'] + + @property + def export_metadata(self) -> Callable[ + [metastore.ExportMetadataRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the export metadata method over gRPC. + + Exports metadata from a service. + + Returns: + Callable[[~.ExportMetadataRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_metadata' not in self._stubs: + self._stubs['export_metadata'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/ExportMetadata', + request_serializer=metastore.ExportMetadataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_metadata'] + + @property + def restore_service(self) -> Callable[ + [metastore.RestoreServiceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the restore service method over gRPC. + + Restores a service from a backup. + + Returns: + Callable[[~.RestoreServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'restore_service' not in self._stubs: + self._stubs['restore_service'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/RestoreService', + request_serializer=metastore.RestoreServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_service'] + + @property + def list_backups(self) -> Callable[ + [metastore.ListBackupsRequest], + Awaitable[metastore.ListBackupsResponse]]: + r"""Return a callable for the list backups method over gRPC. + + Lists backups in a service. + + Returns: + Callable[[~.ListBackupsRequest], + Awaitable[~.ListBackupsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_backups' not in self._stubs: + self._stubs['list_backups'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/ListBackups', + request_serializer=metastore.ListBackupsRequest.serialize, + response_deserializer=metastore.ListBackupsResponse.deserialize, + ) + return self._stubs['list_backups'] + + @property + def get_backup(self) -> Callable[ + [metastore.GetBackupRequest], + Awaitable[metastore.Backup]]: + r"""Return a callable for the get backup method over gRPC. + + Gets details of a single backup. + + Returns: + Callable[[~.GetBackupRequest], + Awaitable[~.Backup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_backup' not in self._stubs: + self._stubs['get_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/GetBackup', + request_serializer=metastore.GetBackupRequest.serialize, + response_deserializer=metastore.Backup.deserialize, + ) + return self._stubs['get_backup'] + + @property + def create_backup(self) -> Callable[ + [metastore.CreateBackupRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create backup method over gRPC. + + Creates a new backup in a given project and location. + + Returns: + Callable[[~.CreateBackupRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_backup' not in self._stubs: + self._stubs['create_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/CreateBackup', + request_serializer=metastore.CreateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_backup'] + + @property + def delete_backup(self) -> Callable[ + [metastore.DeleteBackupRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete backup method over gRPC. + + Deletes a single backup. + + Returns: + Callable[[~.DeleteBackupRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_backup' not in self._stubs: + self._stubs['delete_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/DeleteBackup', + request_serializer=metastore.DeleteBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_backup'] + + @property + def remove_iam_policy(self) -> Callable[ + [metastore.RemoveIamPolicyRequest], + Awaitable[metastore.RemoveIamPolicyResponse]]: + r"""Return a callable for the remove iam policy method over gRPC. + + Removes the attached IAM policies for a resource + + Returns: + Callable[[~.RemoveIamPolicyRequest], + Awaitable[~.RemoveIamPolicyResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_iam_policy' not in self._stubs: + self._stubs['remove_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/RemoveIamPolicy', + request_serializer=metastore.RemoveIamPolicyRequest.serialize, + response_deserializer=metastore.RemoveIamPolicyResponse.deserialize, + ) + return self._stubs['remove_iam_policy'] + + @property + def query_metadata(self) -> Callable[ + [metastore.QueryMetadataRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the query metadata method over gRPC. + + Query DPMS metadata. + + Returns: + Callable[[~.QueryMetadataRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'query_metadata' not in self._stubs: + self._stubs['query_metadata'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/QueryMetadata', + request_serializer=metastore.QueryMetadataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['query_metadata'] + + @property + def move_table_to_database(self) -> Callable[ + [metastore.MoveTableToDatabaseRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the move table to database method over gRPC. + + Move a table to another database. + + Returns: + Callable[[~.MoveTableToDatabaseRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'move_table_to_database' not in self._stubs: + self._stubs['move_table_to_database'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/MoveTableToDatabase', + request_serializer=metastore.MoveTableToDatabaseRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['move_table_to_database'] + + @property + def alter_metadata_resource_location(self) -> Callable[ + [metastore.AlterMetadataResourceLocationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the alter metadata resource + location method over gRPC. + + Alter metadata resource location. The metadata + resource can be a database, table, or partition. This + functionality only updates the parent directory for the + respective metadata resource and does not transfer any + existing data to the new location. + + Returns: + Callable[[~.AlterMetadataResourceLocationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'alter_metadata_resource_location' not in self._stubs: + self._stubs['alter_metadata_resource_location'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastore/AlterMetadataResourceLocation', + request_serializer=metastore.AlterMetadataResourceLocationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['alter_metadata_resource_location'] + + 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 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 set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'DataprocMetastoreGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/rest.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/rest.py new file mode 100644 index 0000000..c934264 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/rest.py @@ -0,0 +1,3218 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +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.metastore_v1beta.types import metastore +from google.longrunning import operations_pb2 # type: ignore + +from .base import DataprocMetastoreTransport, 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 DataprocMetastoreRestInterceptor: + """Interceptor for DataprocMetastore. + + 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 DataprocMetastoreRestTransport. + + .. code-block:: python + class MyCustomDataprocMetastoreInterceptor(DataprocMetastoreRestInterceptor): + def pre_alter_metadata_resource_location(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_alter_metadata_resource_location(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_metadata_import(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_metadata_import(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_export_metadata(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_export_metadata(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_metadata_import(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_metadata_import(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_backups(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_backups(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_metadata_imports(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_metadata_imports(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_services(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_services(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_move_table_to_database(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_move_table_to_database(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_query_metadata(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_query_metadata(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_remove_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_remove_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_restore_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_restore_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_metadata_import(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_metadata_import(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_service(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DataprocMetastoreRestTransport(interceptor=MyCustomDataprocMetastoreInterceptor()) + client = DataprocMetastoreClient(transport=transport) + + + """ + def pre_alter_metadata_resource_location(self, request: metastore.AlterMetadataResourceLocationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.AlterMetadataResourceLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for alter_metadata_resource_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_alter_metadata_resource_location(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for alter_metadata_resource_location + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_create_backup(self, request: metastore.CreateBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.CreateBackupRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_create_backup(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_backup + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_create_metadata_import(self, request: metastore.CreateMetadataImportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.CreateMetadataImportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_metadata_import + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_create_metadata_import(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_metadata_import + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_create_service(self, request: metastore.CreateServiceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.CreateServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_create_service(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_service + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_delete_backup(self, request: metastore.DeleteBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.DeleteBackupRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_delete_backup(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_backup + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_delete_service(self, request: metastore.DeleteServiceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.DeleteServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_delete_service(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_service + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_export_metadata(self, request: metastore.ExportMetadataRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.ExportMetadataRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for export_metadata + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_export_metadata(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for export_metadata + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_get_backup(self, request: metastore.GetBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.GetBackupRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_get_backup(self, response: metastore.Backup) -> metastore.Backup: + """Post-rpc interceptor for get_backup + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_get_metadata_import(self, request: metastore.GetMetadataImportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.GetMetadataImportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_metadata_import + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_get_metadata_import(self, response: metastore.MetadataImport) -> metastore.MetadataImport: + """Post-rpc interceptor for get_metadata_import + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_get_service(self, request: metastore.GetServiceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.GetServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_get_service(self, response: metastore.Service) -> metastore.Service: + """Post-rpc interceptor for get_service + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_list_backups(self, request: metastore.ListBackupsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.ListBackupsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_backups + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_list_backups(self, response: metastore.ListBackupsResponse) -> metastore.ListBackupsResponse: + """Post-rpc interceptor for list_backups + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_list_metadata_imports(self, request: metastore.ListMetadataImportsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.ListMetadataImportsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_metadata_imports + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_list_metadata_imports(self, response: metastore.ListMetadataImportsResponse) -> metastore.ListMetadataImportsResponse: + """Post-rpc interceptor for list_metadata_imports + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_list_services(self, request: metastore.ListServicesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.ListServicesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_services + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_list_services(self, response: metastore.ListServicesResponse) -> metastore.ListServicesResponse: + """Post-rpc interceptor for list_services + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_move_table_to_database(self, request: metastore.MoveTableToDatabaseRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.MoveTableToDatabaseRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for move_table_to_database + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_move_table_to_database(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for move_table_to_database + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_query_metadata(self, request: metastore.QueryMetadataRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.QueryMetadataRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for query_metadata + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_query_metadata(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for query_metadata + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_remove_iam_policy(self, request: metastore.RemoveIamPolicyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.RemoveIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for remove_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_remove_iam_policy(self, response: metastore.RemoveIamPolicyResponse) -> metastore.RemoveIamPolicyResponse: + """Post-rpc interceptor for remove_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_restore_service(self, request: metastore.RestoreServiceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.RestoreServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for restore_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_restore_service(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for restore_service + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_update_metadata_import(self, request: metastore.UpdateMetadataImportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.UpdateMetadataImportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_metadata_import + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_update_metadata_import(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_metadata_import + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_update_service(self, request: metastore.UpdateServiceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore.UpdateServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_update_service(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_service + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore server but before + it is returned to user code. + """ + return response + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastore server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore 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 DataprocMetastore server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DataprocMetastoreRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DataprocMetastoreRestInterceptor + + +class DataprocMetastoreRestTransport(DataprocMetastoreTransport): + """REST backend transport for DataprocMetastore. + + Configures and manages metastore services. Metastore services are + fully managed, highly available, autoscaled, autohealing, OSS-native + deployments of technical metadata management software. Each + metastore service exposes a network endpoint through which metadata + queries are served. Metadata queries can originate from a variety of + sources, including Apache Hive, Apache Presto, and Apache Spark. + + The Dataproc Metastore API defines the following resource model: + + - The service works with a collection of Google Cloud projects, + named: ``/projects/*`` + + - Each project has a collection of available locations, named: + ``/locations/*`` (a location must refer to a Google Cloud + ``region``) + + - Each location has a collection of services, named: + ``/services/*`` + + - Dataproc Metastore services are resources with names of the form: + + ``/projects/{project_number}/locations/{location_id}/services/{service_id}``. + + 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 = 'metastore.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[DataprocMetastoreRestInterceptor] = 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) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DataprocMetastoreRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _AlterMetadataResourceLocation(DataprocMetastoreRestStub): + def __hash__(self): + return hash("AlterMetadataResourceLocation") + + __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: metastore.AlterMetadataResourceLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the alter metadata resource + location method over HTTP. + + Args: + request (~.metastore.AlterMetadataResourceLocationRequest): + The request object. Request message for + [DataprocMetastore.AlterMetadataResourceLocation][google.cloud.metastore.v1beta.DataprocMetastore.AlterMetadataResourceLocation]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{service=projects/*/locations/*/services/*}:alterLocation', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_alter_metadata_resource_location(request, metadata) + pb_request = metastore.AlterMetadataResourceLocationRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_alter_metadata_resource_location(resp) + return resp + + class _CreateBackup(DataprocMetastoreRestStub): + def __hash__(self): + return hash("CreateBackup") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "backupId" : "", } + + @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: metastore.CreateBackupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create backup method over HTTP. + + Args: + request (~.metastore.CreateBackupRequest): + The request object. Request message for + [DataprocMetastore.CreateBackup][google.cloud.metastore.v1beta.DataprocMetastore.CreateBackup]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*/services/*}/backups', + 'body': 'backup', + }, + ] + request, metadata = self._interceptor.pre_create_backup(request, metadata) + pb_request = metastore.CreateBackupRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_backup(resp) + return resp + + class _CreateMetadataImport(DataprocMetastoreRestStub): + def __hash__(self): + return hash("CreateMetadataImport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "metadataImportId" : "", } + + @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: metastore.CreateMetadataImportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create metadata import method over HTTP. + + Args: + request (~.metastore.CreateMetadataImportRequest): + The request object. Request message for + [DataprocMetastore.CreateMetadataImport][google.cloud.metastore.v1beta.DataprocMetastore.CreateMetadataImport]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*/services/*}/metadataImports', + 'body': 'metadata_import', + }, + ] + request, metadata = self._interceptor.pre_create_metadata_import(request, metadata) + pb_request = metastore.CreateMetadataImportRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_metadata_import(resp) + return resp + + class _CreateService(DataprocMetastoreRestStub): + def __hash__(self): + return hash("CreateService") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "serviceId" : "", } + + @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: metastore.CreateServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create service method over HTTP. + + Args: + request (~.metastore.CreateServiceRequest): + The request object. Request message for + [DataprocMetastore.CreateService][google.cloud.metastore.v1beta.DataprocMetastore.CreateService]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*}/services', + 'body': 'service', + }, + ] + request, metadata = self._interceptor.pre_create_service(request, metadata) + pb_request = metastore.CreateServiceRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_service(resp) + return resp + + class _DeleteBackup(DataprocMetastoreRestStub): + def __hash__(self): + return hash("DeleteBackup") + + __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: metastore.DeleteBackupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete backup method over HTTP. + + Args: + request (~.metastore.DeleteBackupRequest): + The request object. Request message for + [DataprocMetastore.DeleteBackup][google.cloud.metastore.v1beta.DataprocMetastore.DeleteBackup]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta/{name=projects/*/locations/*/services/*/backups/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_backup(request, metadata) + pb_request = metastore.DeleteBackupRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_backup(resp) + return resp + + class _DeleteService(DataprocMetastoreRestStub): + def __hash__(self): + return hash("DeleteService") + + __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: metastore.DeleteServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete service method over HTTP. + + Args: + request (~.metastore.DeleteServiceRequest): + The request object. Request message for + [DataprocMetastore.DeleteService][google.cloud.metastore.v1beta.DataprocMetastore.DeleteService]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta/{name=projects/*/locations/*/services/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_service(request, metadata) + pb_request = metastore.DeleteServiceRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_service(resp) + return resp + + class _ExportMetadata(DataprocMetastoreRestStub): + def __hash__(self): + return hash("ExportMetadata") + + __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: metastore.ExportMetadataRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the export metadata method over HTTP. + + Args: + request (~.metastore.ExportMetadataRequest): + The request object. Request message for + [DataprocMetastore.ExportMetadata][google.cloud.metastore.v1beta.DataprocMetastore.ExportMetadata]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{service=projects/*/locations/*/services/*}:exportMetadata', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_export_metadata(request, metadata) + pb_request = metastore.ExportMetadataRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_export_metadata(resp) + return resp + + class _GetBackup(DataprocMetastoreRestStub): + def __hash__(self): + return hash("GetBackup") + + __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: metastore.GetBackupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.Backup: + r"""Call the get backup method over HTTP. + + Args: + request (~.metastore.GetBackupRequest): + The request object. Request message for + [DataprocMetastore.GetBackup][google.cloud.metastore.v1beta.DataprocMetastore.GetBackup]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.Backup: + The details of a backup resource. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/services/*/backups/*}', + }, + ] + request, metadata = self._interceptor.pre_get_backup(request, metadata) + pb_request = metastore.GetBackupRequest.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 = metastore.Backup() + pb_resp = metastore.Backup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_backup(resp) + return resp + + class _GetMetadataImport(DataprocMetastoreRestStub): + def __hash__(self): + return hash("GetMetadataImport") + + __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: metastore.GetMetadataImportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.MetadataImport: + r"""Call the get metadata import method over HTTP. + + Args: + request (~.metastore.GetMetadataImportRequest): + The request object. Request message for + [DataprocMetastore.GetMetadataImport][google.cloud.metastore.v1beta.DataprocMetastore.GetMetadataImport]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.MetadataImport: + A metastore resource that imports + metadata. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/services/*/metadataImports/*}', + }, + ] + request, metadata = self._interceptor.pre_get_metadata_import(request, metadata) + pb_request = metastore.GetMetadataImportRequest.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 = metastore.MetadataImport() + pb_resp = metastore.MetadataImport.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_metadata_import(resp) + return resp + + class _GetService(DataprocMetastoreRestStub): + def __hash__(self): + return hash("GetService") + + __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: metastore.GetServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.Service: + r"""Call the get service method over HTTP. + + Args: + request (~.metastore.GetServiceRequest): + The request object. Request message for + [DataprocMetastore.GetService][google.cloud.metastore.v1beta.DataprocMetastore.GetService]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.Service: + A managed metastore service that + serves metadata queries. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/services/*}', + }, + ] + request, metadata = self._interceptor.pre_get_service(request, metadata) + pb_request = metastore.GetServiceRequest.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 = metastore.Service() + pb_resp = metastore.Service.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_service(resp) + return resp + + class _ListBackups(DataprocMetastoreRestStub): + def __hash__(self): + return hash("ListBackups") + + __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: metastore.ListBackupsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.ListBackupsResponse: + r"""Call the list backups method over HTTP. + + Args: + request (~.metastore.ListBackupsRequest): + The request object. Request message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1beta.DataprocMetastore.ListBackups]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.ListBackupsResponse: + Response message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1beta.DataprocMetastore.ListBackups]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/services/*}/backups', + }, + ] + request, metadata = self._interceptor.pre_list_backups(request, metadata) + pb_request = metastore.ListBackupsRequest.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 = metastore.ListBackupsResponse() + pb_resp = metastore.ListBackupsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_backups(resp) + return resp + + class _ListMetadataImports(DataprocMetastoreRestStub): + def __hash__(self): + return hash("ListMetadataImports") + + __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: metastore.ListMetadataImportsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.ListMetadataImportsResponse: + r"""Call the list metadata imports method over HTTP. + + Args: + request (~.metastore.ListMetadataImportsRequest): + The request object. Request message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1beta.DataprocMetastore.ListMetadataImports]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.ListMetadataImportsResponse: + Response message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1beta.DataprocMetastore.ListMetadataImports]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/services/*}/metadataImports', + }, + ] + request, metadata = self._interceptor.pre_list_metadata_imports(request, metadata) + pb_request = metastore.ListMetadataImportsRequest.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 = metastore.ListMetadataImportsResponse() + pb_resp = metastore.ListMetadataImportsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_metadata_imports(resp) + return resp + + class _ListServices(DataprocMetastoreRestStub): + def __hash__(self): + return hash("ListServices") + + __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: metastore.ListServicesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.ListServicesResponse: + r"""Call the list services method over HTTP. + + Args: + request (~.metastore.ListServicesRequest): + The request object. Request message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1beta.DataprocMetastore.ListServices]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.ListServicesResponse: + Response message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1beta.DataprocMetastore.ListServices]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*}/services', + }, + ] + request, metadata = self._interceptor.pre_list_services(request, metadata) + pb_request = metastore.ListServicesRequest.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 = metastore.ListServicesResponse() + pb_resp = metastore.ListServicesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_services(resp) + return resp + + class _MoveTableToDatabase(DataprocMetastoreRestStub): + def __hash__(self): + return hash("MoveTableToDatabase") + + __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: metastore.MoveTableToDatabaseRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the move table to database method over HTTP. + + Args: + request (~.metastore.MoveTableToDatabaseRequest): + The request object. Request message for + [DataprocMetastore.MoveTableToDatabase][google.cloud.metastore.v1beta.DataprocMetastore.MoveTableToDatabase]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{service=projects/*/locations/*/services/*}:moveTableToDatabase', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_move_table_to_database(request, metadata) + pb_request = metastore.MoveTableToDatabaseRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_move_table_to_database(resp) + return resp + + class _QueryMetadata(DataprocMetastoreRestStub): + def __hash__(self): + return hash("QueryMetadata") + + __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: metastore.QueryMetadataRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the query metadata method over HTTP. + + Args: + request (~.metastore.QueryMetadataRequest): + The request object. Request message for + [DataprocMetastore.QueryMetadata][google.cloud.metastore.v1beta.DataprocMetastore.QueryMetadata]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{service=projects/*/locations/*/services/*}:queryMetadata', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_query_metadata(request, metadata) + pb_request = metastore.QueryMetadataRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_query_metadata(resp) + return resp + + class _RemoveIamPolicy(DataprocMetastoreRestStub): + def __hash__(self): + return hash("RemoveIamPolicy") + + __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: metastore.RemoveIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore.RemoveIamPolicyResponse: + r"""Call the remove iam policy method over HTTP. + + Args: + request (~.metastore.RemoveIamPolicyRequest): + The request object. Request message for + [DataprocMetastore.RemoveIamPolicy][google.cloud.metastore.v1beta.DataprocMetastore.RemoveIamPolicy]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore.RemoveIamPolicyResponse: + Response message for + [DataprocMetastore.RemoveIamPolicy][google.cloud.metastore.v1beta.DataprocMetastore.RemoveIamPolicy]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/**}:removeIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_remove_iam_policy(request, metadata) + pb_request = metastore.RemoveIamPolicyRequest.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 = metastore.RemoveIamPolicyResponse() + pb_resp = metastore.RemoveIamPolicyResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_remove_iam_policy(resp) + return resp + + class _RestoreService(DataprocMetastoreRestStub): + def __hash__(self): + return hash("RestoreService") + + __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: metastore.RestoreServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the restore service method over HTTP. + + Args: + request (~.metastore.RestoreServiceRequest): + The request object. Request message for [DataprocMetastore.Restore][]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{service=projects/*/locations/*/services/*}:restore', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_restore_service(request, metadata) + pb_request = metastore.RestoreServiceRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_restore_service(resp) + return resp + + class _UpdateMetadataImport(DataprocMetastoreRestStub): + def __hash__(self): + return hash("UpdateMetadataImport") + + __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: metastore.UpdateMetadataImportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update metadata import method over HTTP. + + Args: + request (~.metastore.UpdateMetadataImportRequest): + The request object. Request message for + [DataprocMetastore.UpdateMetadataImport][google.cloud.metastore.v1beta.DataprocMetastore.UpdateMetadataImport]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta/{metadata_import.name=projects/*/locations/*/services/*/metadataImports/*}', + 'body': 'metadata_import', + }, + ] + request, metadata = self._interceptor.pre_update_metadata_import(request, metadata) + pb_request = metastore.UpdateMetadataImportRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_metadata_import(resp) + return resp + + class _UpdateService(DataprocMetastoreRestStub): + def __hash__(self): + return hash("UpdateService") + + __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: metastore.UpdateServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update service method over HTTP. + + Args: + request (~.metastore.UpdateServiceRequest): + The request object. Request message for + [DataprocMetastore.UpdateService][google.cloud.metastore.v1beta.DataprocMetastore.UpdateService]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta/{service.name=projects/*/locations/*/services/*}', + 'body': 'service', + }, + ] + request, metadata = self._interceptor.pre_update_service(request, metadata) + pb_request = metastore.UpdateServiceRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_service(resp) + return resp + + @property + def alter_metadata_resource_location(self) -> Callable[ + [metastore.AlterMetadataResourceLocationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AlterMetadataResourceLocation(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_backup(self) -> Callable[ + [metastore.CreateBackupRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_metadata_import(self) -> Callable[ + [metastore.CreateMetadataImportRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateMetadataImport(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_service(self) -> Callable[ + [metastore.CreateServiceRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateService(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_backup(self) -> Callable[ + [metastore.DeleteBackupRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_service(self) -> Callable[ + [metastore.DeleteServiceRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteService(self._session, self._host, self._interceptor) # type: ignore + + @property + def export_metadata(self) -> Callable[ + [metastore.ExportMetadataRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ExportMetadata(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_backup(self) -> Callable[ + [metastore.GetBackupRequest], + metastore.Backup]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_metadata_import(self) -> Callable[ + [metastore.GetMetadataImportRequest], + metastore.MetadataImport]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetMetadataImport(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_service(self) -> Callable[ + [metastore.GetServiceRequest], + metastore.Service]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetService(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_backups(self) -> Callable[ + [metastore.ListBackupsRequest], + metastore.ListBackupsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListBackups(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_metadata_imports(self) -> Callable[ + [metastore.ListMetadataImportsRequest], + metastore.ListMetadataImportsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListMetadataImports(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_services(self) -> Callable[ + [metastore.ListServicesRequest], + metastore.ListServicesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListServices(self._session, self._host, self._interceptor) # type: ignore + + @property + def move_table_to_database(self) -> Callable[ + [metastore.MoveTableToDatabaseRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._MoveTableToDatabase(self._session, self._host, self._interceptor) # type: ignore + + @property + def query_metadata(self) -> Callable[ + [metastore.QueryMetadataRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._QueryMetadata(self._session, self._host, self._interceptor) # type: ignore + + @property + def remove_iam_policy(self) -> Callable[ + [metastore.RemoveIamPolicyRequest], + metastore.RemoveIamPolicyResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RemoveIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def restore_service(self) -> Callable[ + [metastore.RestoreServiceRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RestoreService(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_metadata_import(self) -> Callable[ + [metastore.UpdateMetadataImportRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMetadataImport(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_service(self) -> Callable[ + [metastore.UpdateServiceRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateService(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(DataprocMetastoreRestStub): + 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': '/v1beta/{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(DataprocMetastoreRestStub): + 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': '/v1beta/{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 get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(DataprocMetastoreRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy 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: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/backups/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/databases/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/databases/*/tables/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{resource=projects/*/locations/*/federations/*}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(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 = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(DataprocMetastoreRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy 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: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/backups/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/databases/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/databases/*/tables/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/federations/*}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.loads(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) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(DataprocMetastoreRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions 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: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/backups/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/databases/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/databases/*/tables/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/federations/*}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.loads(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) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(DataprocMetastoreRestStub): + 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': '/v1beta/{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(DataprocMetastoreRestStub): + 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': '/v1beta/{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(DataprocMetastoreRestStub): + 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': '/v1beta/{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__=( + 'DataprocMetastoreRestTransport', +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/__init__.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/__init__.py new file mode 100644 index 0000000..7029be0 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import DataprocMetastoreFederationClient +from .async_client import DataprocMetastoreFederationAsyncClient + +__all__ = ( + 'DataprocMetastoreFederationClient', + 'DataprocMetastoreFederationAsyncClient', +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/async_client.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/async_client.py new file mode 100644 index 0000000..94e5083 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/async_client.py @@ -0,0 +1,1388 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.metastore_v1beta import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1beta.services.dataproc_metastore_federation import pagers +from google.cloud.metastore_v1beta.types import metastore +from google.cloud.metastore_v1beta.types import metastore_federation +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DataprocMetastoreFederationTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DataprocMetastoreFederationGrpcAsyncIOTransport +from .client import DataprocMetastoreFederationClient + + +class DataprocMetastoreFederationAsyncClient: + """Configures and manages metastore federation services. Dataproc + Metastore Federation Service allows federating a collection of + backend metastores like BigQuery, Dataplex Lakes, and other Dataproc + Metastores. The Federation Service exposes a gRPC URL through which + metadata from the backend metastores are served at query time. + + The Dataproc Metastore Federation API defines the following resource + model: + + - The service works with a collection of Google Cloud projects. + - Each project has a collection of available locations. + - Each location has a collection of federations. + - Dataproc Metastore Federations are resources with names of the + form: + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + """ + + _client: DataprocMetastoreFederationClient + + DEFAULT_ENDPOINT = DataprocMetastoreFederationClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DataprocMetastoreFederationClient.DEFAULT_MTLS_ENDPOINT + + federation_path = staticmethod(DataprocMetastoreFederationClient.federation_path) + parse_federation_path = staticmethod(DataprocMetastoreFederationClient.parse_federation_path) + common_billing_account_path = staticmethod(DataprocMetastoreFederationClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DataprocMetastoreFederationClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DataprocMetastoreFederationClient.common_folder_path) + parse_common_folder_path = staticmethod(DataprocMetastoreFederationClient.parse_common_folder_path) + common_organization_path = staticmethod(DataprocMetastoreFederationClient.common_organization_path) + parse_common_organization_path = staticmethod(DataprocMetastoreFederationClient.parse_common_organization_path) + common_project_path = staticmethod(DataprocMetastoreFederationClient.common_project_path) + parse_common_project_path = staticmethod(DataprocMetastoreFederationClient.parse_common_project_path) + common_location_path = staticmethod(DataprocMetastoreFederationClient.common_location_path) + parse_common_location_path = staticmethod(DataprocMetastoreFederationClient.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: + DataprocMetastoreFederationAsyncClient: The constructed client. + """ + return DataprocMetastoreFederationClient.from_service_account_info.__func__(DataprocMetastoreFederationAsyncClient, 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: + DataprocMetastoreFederationAsyncClient: The constructed client. + """ + return DataprocMetastoreFederationClient.from_service_account_file.__func__(DataprocMetastoreFederationAsyncClient, 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 DataprocMetastoreFederationClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DataprocMetastoreFederationTransport: + """Returns the transport used by the client instance. + + Returns: + DataprocMetastoreFederationTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DataprocMetastoreFederationClient).get_transport_class, type(DataprocMetastoreFederationClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DataprocMetastoreFederationTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dataproc metastore federation 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, ~.DataprocMetastoreFederationTransport]): 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 = DataprocMetastoreFederationClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_federations(self, + request: Optional[Union[metastore_federation.ListFederationsRequest, 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.ListFederationsAsyncPager: + r"""Lists federations in a 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 metastore_v1beta + + async def sample_list_federations(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.ListFederationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_federations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.ListFederationsRequest, dict]]): + The request object. Request message for ListFederations. + parent (:class:`str`): + Required. The relative resource name of the location of + metastore federations to list, in the following form: + ``projects/{project_number}/locations/{location_id}``. + + 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.metastore_v1beta.services.dataproc_metastore_federation.pagers.ListFederationsAsyncPager: + Response message for ListFederations + 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 = metastore_federation.ListFederationsRequest(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_federations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListFederationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_federation(self, + request: Optional[Union[metastore_federation.GetFederationRequest, 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]] = (), + ) -> metastore_federation.Federation: + r"""Gets the details of a single federation. + + .. 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 metastore_v1beta + + async def sample_get_federation(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.GetFederationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_federation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.GetFederationRequest, dict]]): + The request object. Request message for GetFederation. + name (:class:`str`): + Required. The relative resource name of the metastore + federation to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + 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.metastore_v1beta.types.Federation: + Represents a federation of multiple + backend metastores. + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 = metastore_federation.GetFederationRequest(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_federation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_federation(self, + request: Optional[Union[metastore_federation.CreateFederationRequest, dict]] = None, + *, + parent: Optional[str] = None, + federation: Optional[metastore_federation.Federation] = None, + federation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a metastore federation in a 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 metastore_v1beta + + async def sample_create_federation(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.CreateFederationRequest( + parent="parent_value", + federation_id="federation_id_value", + ) + + # Make the request + operation = client.create_federation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.CreateFederationRequest, dict]]): + The request object. Request message for CreateFederation. + parent (:class:`str`): + Required. The relative resource name of the location in + which to create a federation service, in the following + form: + + ``projects/{project_number}/locations/{location_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + federation (:class:`google.cloud.metastore_v1beta.types.Federation`): + Required. The Metastore Federation to create. The + ``name`` field is ignored. The ID of the created + metastore federation must be provided in the request's + ``federation_id`` field. + + This corresponds to the ``federation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + federation_id (:class:`str`): + Required. The ID of the metastore + federation, which is used as the final + component of the metastore federation's + name. + This value must be between 2 and 63 + characters long inclusive, begin with a + letter, end with a letter or number, and + consist of alpha-numeric ASCII + characters or hyphens. + + This corresponds to the ``federation_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1beta.types.Federation` + Represents a federation of multiple backend metastores. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, federation, federation_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = metastore_federation.CreateFederationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if federation is not None: + request.federation = federation + if federation_id is not None: + request.federation_id = federation_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_federation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore_federation.Federation, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_federation(self, + request: Optional[Union[metastore_federation.UpdateFederationRequest, dict]] = None, + *, + federation: Optional[metastore_federation.Federation] = 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the fields of a federation. + + .. 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 metastore_v1beta + + async def sample_update_federation(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.UpdateFederationRequest( + ) + + # Make the request + operation = client.update_federation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.UpdateFederationRequest, dict]]): + The request object. Request message for UpdateFederation. + federation (:class:`google.cloud.metastore_v1beta.types.Federation`): + Required. The metastore federation to update. The server + only merges fields in the service if they are specified + in ``update_mask``. + + The metastore federation's ``name`` field is used to + identify the metastore service to be updated. + + This corresponds to the ``federation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. A field mask used to specify the fields to be + overwritten in the metastore federation resource by the + update. Fields specified in the ``update_mask`` are + relative to the resource (not to the full request). A + field is overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1beta.types.Federation` + Represents a federation of multiple backend metastores. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([federation, 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 = metastore_federation.UpdateFederationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if federation is not None: + request.federation = federation + 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_federation, + 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(( + ("federation.name", request.federation.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + metastore_federation.Federation, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_federation(self, + request: Optional[Union[metastore_federation.DeleteFederationRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single federation. + + .. 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 metastore_v1beta + + async def sample_delete_federation(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.DeleteFederationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_federation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.metastore_v1beta.types.DeleteFederationRequest, dict]]): + The request object. Request message for DeleteFederation. + name (:class:`str`): + Required. The relative resource name of the metastore + federation to delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 = metastore_federation.DeleteFederationRequest(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_federation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=metastore.OperationMetadata, + ) + + # 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.set_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.GetIamPolicyRequest(**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_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.test_iam_permissions, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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): + 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__ = ( + "DataprocMetastoreFederationAsyncClient", +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/client.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/client.py new file mode 100644 index 0000000..66cc2b6 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/client.py @@ -0,0 +1,1587 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.metastore_v1beta import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1beta.services.dataproc_metastore_federation import pagers +from google.cloud.metastore_v1beta.types import metastore +from google.cloud.metastore_v1beta.types import metastore_federation +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DataprocMetastoreFederationTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DataprocMetastoreFederationGrpcTransport +from .transports.grpc_asyncio import DataprocMetastoreFederationGrpcAsyncIOTransport +from .transports.rest import DataprocMetastoreFederationRestTransport + + +class DataprocMetastoreFederationClientMeta(type): + """Metaclass for the DataprocMetastoreFederation 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[DataprocMetastoreFederationTransport]] + _transport_registry["grpc"] = DataprocMetastoreFederationGrpcTransport + _transport_registry["grpc_asyncio"] = DataprocMetastoreFederationGrpcAsyncIOTransport + _transport_registry["rest"] = DataprocMetastoreFederationRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[DataprocMetastoreFederationTransport]: + """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 DataprocMetastoreFederationClient(metaclass=DataprocMetastoreFederationClientMeta): + """Configures and manages metastore federation services. Dataproc + Metastore Federation Service allows federating a collection of + backend metastores like BigQuery, Dataplex Lakes, and other Dataproc + Metastores. The Federation Service exposes a gRPC URL through which + metadata from the backend metastores are served at query time. + + The Dataproc Metastore Federation API defines the following resource + model: + + - The service works with a collection of Google Cloud projects. + - Each project has a collection of available locations. + - Each location has a collection of federations. + - Dataproc Metastore Federations are resources with names of the + form: + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + """ + + @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 = "metastore.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: + DataprocMetastoreFederationClient: 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: + DataprocMetastoreFederationClient: 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) -> DataprocMetastoreFederationTransport: + """Returns the transport used by the client instance. + + Returns: + DataprocMetastoreFederationTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def federation_path(project: str,location: str,federation: str,) -> str: + """Returns a fully-qualified federation string.""" + return "projects/{project}/locations/{location}/federations/{federation}".format(project=project, location=location, federation=federation, ) + + @staticmethod + def parse_federation_path(path: str) -> Dict[str,str]: + """Parses a federation path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/federations/(?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, DataprocMetastoreFederationTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dataproc metastore federation 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, DataprocMetastoreFederationTransport]): 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, DataprocMetastoreFederationTransport): + # transport is a DataprocMetastoreFederationTransport 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_federations(self, + request: Optional[Union[metastore_federation.ListFederationsRequest, 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.ListFederationsPager: + r"""Lists federations in a 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 metastore_v1beta + + def sample_list_federations(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1beta.ListFederationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_federations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.ListFederationsRequest, dict]): + The request object. Request message for ListFederations. + parent (str): + Required. The relative resource name of the location of + metastore federations to list, in the following form: + ``projects/{project_number}/locations/{location_id}``. + + 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.metastore_v1beta.services.dataproc_metastore_federation.pagers.ListFederationsPager: + Response message for ListFederations + 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 metastore_federation.ListFederationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore_federation.ListFederationsRequest): + request = metastore_federation.ListFederationsRequest(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_federations] + + # Certain 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.ListFederationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_federation(self, + request: Optional[Union[metastore_federation.GetFederationRequest, 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]] = (), + ) -> metastore_federation.Federation: + r"""Gets the details of a single federation. + + .. 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 metastore_v1beta + + def sample_get_federation(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1beta.GetFederationRequest( + name="name_value", + ) + + # Make the request + response = client.get_federation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.GetFederationRequest, dict]): + The request object. Request message for GetFederation. + name (str): + Required. The relative resource name of the metastore + federation to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + 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.metastore_v1beta.types.Federation: + Represents a federation of multiple + backend metastores. + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 metastore_federation.GetFederationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore_federation.GetFederationRequest): + request = metastore_federation.GetFederationRequest(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_federation] + + # Certain 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_federation(self, + request: Optional[Union[metastore_federation.CreateFederationRequest, dict]] = None, + *, + parent: Optional[str] = None, + federation: Optional[metastore_federation.Federation] = None, + federation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a metastore federation in a 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 metastore_v1beta + + def sample_create_federation(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1beta.CreateFederationRequest( + parent="parent_value", + federation_id="federation_id_value", + ) + + # Make the request + operation = client.create_federation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.CreateFederationRequest, dict]): + The request object. Request message for CreateFederation. + parent (str): + Required. The relative resource name of the location in + which to create a federation service, in the following + form: + + ``projects/{project_number}/locations/{location_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + federation (google.cloud.metastore_v1beta.types.Federation): + Required. The Metastore Federation to create. The + ``name`` field is ignored. The ID of the created + metastore federation must be provided in the request's + ``federation_id`` field. + + This corresponds to the ``federation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + federation_id (str): + Required. The ID of the metastore + federation, which is used as the final + component of the metastore federation's + name. + This value must be between 2 and 63 + characters long inclusive, begin with a + letter, end with a letter or number, and + consist of alpha-numeric ASCII + characters or hyphens. + + This corresponds to the ``federation_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1beta.types.Federation` + Represents a federation of multiple backend metastores. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, federation, federation_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a metastore_federation.CreateFederationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore_federation.CreateFederationRequest): + request = metastore_federation.CreateFederationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if federation is not None: + request.federation = federation + if federation_id is not None: + request.federation_id = federation_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_federation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore_federation.Federation, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_federation(self, + request: Optional[Union[metastore_federation.UpdateFederationRequest, dict]] = None, + *, + federation: Optional[metastore_federation.Federation] = 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]] = (), + ) -> operation.Operation: + r"""Updates the fields of a federation. + + .. 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 metastore_v1beta + + def sample_update_federation(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1beta.UpdateFederationRequest( + ) + + # Make the request + operation = client.update_federation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.UpdateFederationRequest, dict]): + The request object. Request message for UpdateFederation. + federation (google.cloud.metastore_v1beta.types.Federation): + Required. The metastore federation to update. The server + only merges fields in the service if they are specified + in ``update_mask``. + + The metastore federation's ``name`` field is used to + identify the metastore service to be updated. + + This corresponds to the ``federation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask used to specify the fields to be + overwritten in the metastore federation resource by the + update. Fields specified in the ``update_mask`` are + relative to the resource (not to the full request). A + field is overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.metastore_v1beta.types.Federation` + Represents a federation of multiple backend metastores. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([federation, 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 metastore_federation.UpdateFederationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore_federation.UpdateFederationRequest): + request = metastore_federation.UpdateFederationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if federation is not None: + request.federation = federation + 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_federation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("federation.name", request.federation.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + metastore_federation.Federation, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_federation(self, + request: Optional[Union[metastore_federation.DeleteFederationRequest, 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]] = (), + ) -> operation.Operation: + r"""Deletes a single federation. + + .. 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 metastore_v1beta + + def sample_delete_federation(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1beta.DeleteFederationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_federation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.metastore_v1beta.types.DeleteFederationRequest, dict]): + The request object. Request message for DeleteFederation. + name (str): + Required. The relative resource name of the metastore + federation to delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: 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 metastore_federation.DeleteFederationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, metastore_federation.DeleteFederationRequest): + request = metastore_federation.DeleteFederationRequest(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_federation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=metastore.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "DataprocMetastoreFederationClient": + 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` 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 = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + 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( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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__ = ( + "DataprocMetastoreFederationClient", +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/pagers.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/pagers.py new file mode 100644 index 0000000..4941e69 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.metastore_v1beta.types import metastore_federation + + +class ListFederationsPager: + """A pager for iterating through ``list_federations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1beta.types.ListFederationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``federations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFederations`` requests and continue to iterate + through the ``federations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1beta.types.ListFederationsResponse` + 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[..., metastore_federation.ListFederationsResponse], + request: metastore_federation.ListFederationsRequest, + response: metastore_federation.ListFederationsResponse, + *, + 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.metastore_v1beta.types.ListFederationsRequest): + The initial request object. + response (google.cloud.metastore_v1beta.types.ListFederationsResponse): + 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 = metastore_federation.ListFederationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[metastore_federation.ListFederationsResponse]: + 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[metastore_federation.Federation]: + for page in self.pages: + yield from page.federations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFederationsAsyncPager: + """A pager for iterating through ``list_federations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.metastore_v1beta.types.ListFederationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``federations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFederations`` requests and continue to iterate + through the ``federations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.metastore_v1beta.types.ListFederationsResponse` + 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[metastore_federation.ListFederationsResponse]], + request: metastore_federation.ListFederationsRequest, + response: metastore_federation.ListFederationsResponse, + *, + 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.metastore_v1beta.types.ListFederationsRequest): + The initial request object. + response (google.cloud.metastore_v1beta.types.ListFederationsResponse): + 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 = metastore_federation.ListFederationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[metastore_federation.ListFederationsResponse]: + 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[metastore_federation.Federation]: + async def async_generator(): + async for page in self.pages: + for response in page.federations: + 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/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/__init__.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/__init__.py new file mode 100644 index 0000000..0ba9a1b --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import DataprocMetastoreFederationTransport +from .grpc import DataprocMetastoreFederationGrpcTransport +from .grpc_asyncio import DataprocMetastoreFederationGrpcAsyncIOTransport +from .rest import DataprocMetastoreFederationRestTransport +from .rest import DataprocMetastoreFederationRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DataprocMetastoreFederationTransport]] +_transport_registry['grpc'] = DataprocMetastoreFederationGrpcTransport +_transport_registry['grpc_asyncio'] = DataprocMetastoreFederationGrpcAsyncIOTransport +_transport_registry['rest'] = DataprocMetastoreFederationRestTransport + +__all__ = ( + 'DataprocMetastoreFederationTransport', + 'DataprocMetastoreFederationGrpcTransport', + 'DataprocMetastoreFederationGrpcAsyncIOTransport', + 'DataprocMetastoreFederationRestTransport', + 'DataprocMetastoreFederationRestInterceptor', +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/base.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/base.py new file mode 100644 index 0000000..2a57db6 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/base.py @@ -0,0 +1,288 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.metastore_v1beta import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1beta.types import metastore_federation +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class DataprocMetastoreFederationTransport(abc.ABC): + """Abstract transport class for DataprocMetastoreFederation.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'metastore.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_federations: gapic_v1.method.wrap_method( + self.list_federations, + default_timeout=None, + client_info=client_info, + ), + self.get_federation: gapic_v1.method.wrap_method( + self.get_federation, + default_timeout=None, + client_info=client_info, + ), + self.create_federation: gapic_v1.method.wrap_method( + self.create_federation, + default_timeout=None, + client_info=client_info, + ), + self.update_federation: gapic_v1.method.wrap_method( + self.update_federation, + default_timeout=None, + client_info=client_info, + ), + self.delete_federation: gapic_v1.method.wrap_method( + self.delete_federation, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_federations(self) -> Callable[ + [metastore_federation.ListFederationsRequest], + Union[ + metastore_federation.ListFederationsResponse, + Awaitable[metastore_federation.ListFederationsResponse] + ]]: + raise NotImplementedError() + + @property + def get_federation(self) -> Callable[ + [metastore_federation.GetFederationRequest], + Union[ + metastore_federation.Federation, + Awaitable[metastore_federation.Federation] + ]]: + raise NotImplementedError() + + @property + def create_federation(self) -> Callable[ + [metastore_federation.CreateFederationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_federation(self) -> Callable[ + [metastore_federation.UpdateFederationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_federation(self) -> Callable[ + [metastore_federation.DeleteFederationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + 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 delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + 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__ = ( + 'DataprocMetastoreFederationTransport', +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/grpc.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/grpc.py new file mode 100644 index 0000000..090f7b7 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/grpc.py @@ -0,0 +1,575 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1beta.types import metastore_federation +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from .base import DataprocMetastoreFederationTransport, DEFAULT_CLIENT_INFO + + +class DataprocMetastoreFederationGrpcTransport(DataprocMetastoreFederationTransport): + """gRPC backend transport for DataprocMetastoreFederation. + + Configures and manages metastore federation services. Dataproc + Metastore Federation Service allows federating a collection of + backend metastores like BigQuery, Dataplex Lakes, and other Dataproc + Metastores. The Federation Service exposes a gRPC URL through which + metadata from the backend metastores are served at query time. + + The Dataproc Metastore Federation API defines the following resource + model: + + - The service works with a collection of Google Cloud projects. + - Each project has a collection of available locations. + - Each location has a collection of federations. + - Dataproc Metastore Federations are resources with names of the + form: + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + 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 = 'metastore.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] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + 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 = 'metastore.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 operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_federations(self) -> Callable[ + [metastore_federation.ListFederationsRequest], + metastore_federation.ListFederationsResponse]: + r"""Return a callable for the list federations method over gRPC. + + Lists federations in a project and location. + + Returns: + Callable[[~.ListFederationsRequest], + ~.ListFederationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_federations' not in self._stubs: + self._stubs['list_federations'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastoreFederation/ListFederations', + request_serializer=metastore_federation.ListFederationsRequest.serialize, + response_deserializer=metastore_federation.ListFederationsResponse.deserialize, + ) + return self._stubs['list_federations'] + + @property + def get_federation(self) -> Callable[ + [metastore_federation.GetFederationRequest], + metastore_federation.Federation]: + r"""Return a callable for the get federation method over gRPC. + + Gets the details of a single federation. + + Returns: + Callable[[~.GetFederationRequest], + ~.Federation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_federation' not in self._stubs: + self._stubs['get_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastoreFederation/GetFederation', + request_serializer=metastore_federation.GetFederationRequest.serialize, + response_deserializer=metastore_federation.Federation.deserialize, + ) + return self._stubs['get_federation'] + + @property + def create_federation(self) -> Callable[ + [metastore_federation.CreateFederationRequest], + operations_pb2.Operation]: + r"""Return a callable for the create federation method over gRPC. + + Creates a metastore federation in a project and + location. + + Returns: + Callable[[~.CreateFederationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_federation' not in self._stubs: + self._stubs['create_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastoreFederation/CreateFederation', + request_serializer=metastore_federation.CreateFederationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_federation'] + + @property + def update_federation(self) -> Callable[ + [metastore_federation.UpdateFederationRequest], + operations_pb2.Operation]: + r"""Return a callable for the update federation method over gRPC. + + Updates the fields of a federation. + + Returns: + Callable[[~.UpdateFederationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_federation' not in self._stubs: + self._stubs['update_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastoreFederation/UpdateFederation', + request_serializer=metastore_federation.UpdateFederationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_federation'] + + @property + def delete_federation(self) -> Callable[ + [metastore_federation.DeleteFederationRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete federation method over gRPC. + + Deletes a single federation. + + Returns: + Callable[[~.DeleteFederationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_federation' not in self._stubs: + self._stubs['delete_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastoreFederation/DeleteFederation', + request_serializer=metastore_federation.DeleteFederationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_federation'] + + 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 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 set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'DataprocMetastoreFederationGrpcTransport', +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/grpc_asyncio.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/grpc_asyncio.py new file mode 100644 index 0000000..aa943f5 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/grpc_asyncio.py @@ -0,0 +1,574 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.metastore_v1beta.types import metastore_federation +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from .base import DataprocMetastoreFederationTransport, DEFAULT_CLIENT_INFO +from .grpc import DataprocMetastoreFederationGrpcTransport + + +class DataprocMetastoreFederationGrpcAsyncIOTransport(DataprocMetastoreFederationTransport): + """gRPC AsyncIO backend transport for DataprocMetastoreFederation. + + Configures and manages metastore federation services. Dataproc + Metastore Federation Service allows federating a collection of + backend metastores like BigQuery, Dataplex Lakes, and other Dataproc + Metastores. The Federation Service exposes a gRPC URL through which + metadata from the backend metastores are served at query time. + + The Dataproc Metastore Federation API defines the following resource + model: + + - The service works with a collection of Google Cloud projects. + - Each project has a collection of available locations. + - Each location has a collection of federations. + - Dataproc Metastore Federations are resources with names of the + form: + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + 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 = 'metastore.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 = 'metastore.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] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + 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 operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_federations(self) -> Callable[ + [metastore_federation.ListFederationsRequest], + Awaitable[metastore_federation.ListFederationsResponse]]: + r"""Return a callable for the list federations method over gRPC. + + Lists federations in a project and location. + + Returns: + Callable[[~.ListFederationsRequest], + Awaitable[~.ListFederationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_federations' not in self._stubs: + self._stubs['list_federations'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastoreFederation/ListFederations', + request_serializer=metastore_federation.ListFederationsRequest.serialize, + response_deserializer=metastore_federation.ListFederationsResponse.deserialize, + ) + return self._stubs['list_federations'] + + @property + def get_federation(self) -> Callable[ + [metastore_federation.GetFederationRequest], + Awaitable[metastore_federation.Federation]]: + r"""Return a callable for the get federation method over gRPC. + + Gets the details of a single federation. + + Returns: + Callable[[~.GetFederationRequest], + Awaitable[~.Federation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_federation' not in self._stubs: + self._stubs['get_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastoreFederation/GetFederation', + request_serializer=metastore_federation.GetFederationRequest.serialize, + response_deserializer=metastore_federation.Federation.deserialize, + ) + return self._stubs['get_federation'] + + @property + def create_federation(self) -> Callable[ + [metastore_federation.CreateFederationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create federation method over gRPC. + + Creates a metastore federation in a project and + location. + + Returns: + Callable[[~.CreateFederationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_federation' not in self._stubs: + self._stubs['create_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastoreFederation/CreateFederation', + request_serializer=metastore_federation.CreateFederationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_federation'] + + @property + def update_federation(self) -> Callable[ + [metastore_federation.UpdateFederationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update federation method over gRPC. + + Updates the fields of a federation. + + Returns: + Callable[[~.UpdateFederationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_federation' not in self._stubs: + self._stubs['update_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastoreFederation/UpdateFederation', + request_serializer=metastore_federation.UpdateFederationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_federation'] + + @property + def delete_federation(self) -> Callable[ + [metastore_federation.DeleteFederationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete federation method over gRPC. + + Deletes a single federation. + + Returns: + Callable[[~.DeleteFederationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_federation' not in self._stubs: + self._stubs['delete_federation'] = self.grpc_channel.unary_unary( + '/google.cloud.metastore.v1beta.DataprocMetastoreFederation/DeleteFederation', + request_serializer=metastore_federation.DeleteFederationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_federation'] + + 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 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 set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'DataprocMetastoreFederationGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/rest.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/rest.py new file mode 100644 index 0000000..b9334df --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/rest.py @@ -0,0 +1,1552 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +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.metastore_v1beta.types import metastore_federation +from google.longrunning import operations_pb2 # type: ignore + +from .base import DataprocMetastoreFederationTransport, 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 DataprocMetastoreFederationRestInterceptor: + """Interceptor for DataprocMetastoreFederation. + + 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 DataprocMetastoreFederationRestTransport. + + .. code-block:: python + class MyCustomDataprocMetastoreFederationInterceptor(DataprocMetastoreFederationRestInterceptor): + def pre_create_federation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_federation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_federation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_federation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_federation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_federation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_federations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_federations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_federation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_federation(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DataprocMetastoreFederationRestTransport(interceptor=MyCustomDataprocMetastoreFederationInterceptor()) + client = DataprocMetastoreFederationClient(transport=transport) + + + """ + def pre_create_federation(self, request: metastore_federation.CreateFederationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore_federation.CreateFederationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_federation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_create_federation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_federation + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_delete_federation(self, request: metastore_federation.DeleteFederationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore_federation.DeleteFederationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_federation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_delete_federation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_federation + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_get_federation(self, request: metastore_federation.GetFederationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore_federation.GetFederationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_federation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_get_federation(self, response: metastore_federation.Federation) -> metastore_federation.Federation: + """Post-rpc interceptor for get_federation + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_list_federations(self, request: metastore_federation.ListFederationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore_federation.ListFederationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_federations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_list_federations(self, response: metastore_federation.ListFederationsResponse) -> metastore_federation.ListFederationsResponse: + """Post-rpc interceptor for list_federations + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_update_federation(self, request: metastore_federation.UpdateFederationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[metastore_federation.UpdateFederationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_federation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_update_federation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_federation + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataprocMetastoreFederation server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation 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 DataprocMetastoreFederation server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DataprocMetastoreFederationRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DataprocMetastoreFederationRestInterceptor + + +class DataprocMetastoreFederationRestTransport(DataprocMetastoreFederationTransport): + """REST backend transport for DataprocMetastoreFederation. + + Configures and manages metastore federation services. Dataproc + Metastore Federation Service allows federating a collection of + backend metastores like BigQuery, Dataplex Lakes, and other Dataproc + Metastores. The Federation Service exposes a gRPC URL through which + metadata from the backend metastores are served at query time. + + The Dataproc Metastore Federation API defines the following resource + model: + + - The service works with a collection of Google Cloud projects. + - Each project has a collection of available locations. + - Each location has a collection of federations. + - Dataproc Metastore Federations are resources with names of the + form: + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + + 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 = 'metastore.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[DataprocMetastoreFederationRestInterceptor] = 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) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DataprocMetastoreFederationRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateFederation(DataprocMetastoreFederationRestStub): + def __hash__(self): + return hash("CreateFederation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "federationId" : "", } + + @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: metastore_federation.CreateFederationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create federation method over HTTP. + + Args: + request (~.metastore_federation.CreateFederationRequest): + The request object. Request message for CreateFederation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*}/federations', + 'body': 'federation', + }, + ] + request, metadata = self._interceptor.pre_create_federation(request, metadata) + pb_request = metastore_federation.CreateFederationRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_federation(resp) + return resp + + class _DeleteFederation(DataprocMetastoreFederationRestStub): + def __hash__(self): + return hash("DeleteFederation") + + __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: metastore_federation.DeleteFederationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete federation method over HTTP. + + Args: + request (~.metastore_federation.DeleteFederationRequest): + The request object. Request message for DeleteFederation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta/{name=projects/*/locations/*/federations/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_federation(request, metadata) + pb_request = metastore_federation.DeleteFederationRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_federation(resp) + return resp + + class _GetFederation(DataprocMetastoreFederationRestStub): + def __hash__(self): + return hash("GetFederation") + + __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: metastore_federation.GetFederationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore_federation.Federation: + r"""Call the get federation method over HTTP. + + Args: + request (~.metastore_federation.GetFederationRequest): + The request object. Request message for GetFederation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore_federation.Federation: + Represents a federation of multiple + backend metastores. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/federations/*}', + }, + ] + request, metadata = self._interceptor.pre_get_federation(request, metadata) + pb_request = metastore_federation.GetFederationRequest.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 = metastore_federation.Federation() + pb_resp = metastore_federation.Federation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_federation(resp) + return resp + + class _ListFederations(DataprocMetastoreFederationRestStub): + def __hash__(self): + return hash("ListFederations") + + __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: metastore_federation.ListFederationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> metastore_federation.ListFederationsResponse: + r"""Call the list federations method over HTTP. + + Args: + request (~.metastore_federation.ListFederationsRequest): + The request object. Request message for ListFederations. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.metastore_federation.ListFederationsResponse: + Response message for ListFederations + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*}/federations', + }, + ] + request, metadata = self._interceptor.pre_list_federations(request, metadata) + pb_request = metastore_federation.ListFederationsRequest.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 = metastore_federation.ListFederationsResponse() + pb_resp = metastore_federation.ListFederationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_federations(resp) + return resp + + class _UpdateFederation(DataprocMetastoreFederationRestStub): + def __hash__(self): + return hash("UpdateFederation") + + __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: metastore_federation.UpdateFederationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update federation method over HTTP. + + Args: + request (~.metastore_federation.UpdateFederationRequest): + The request object. Request message for UpdateFederation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta/{federation.name=projects/*/locations/*/federations/*}', + 'body': 'federation', + }, + ] + request, metadata = self._interceptor.pre_update_federation(request, metadata) + pb_request = metastore_federation.UpdateFederationRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_federation(resp) + return resp + + @property + def create_federation(self) -> Callable[ + [metastore_federation.CreateFederationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateFederation(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_federation(self) -> Callable[ + [metastore_federation.DeleteFederationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteFederation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_federation(self) -> Callable[ + [metastore_federation.GetFederationRequest], + metastore_federation.Federation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetFederation(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_federations(self) -> Callable[ + [metastore_federation.ListFederationsRequest], + metastore_federation.ListFederationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListFederations(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_federation(self) -> Callable[ + [metastore_federation.UpdateFederationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateFederation(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(DataprocMetastoreFederationRestStub): + 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': '/v1beta/{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(DataprocMetastoreFederationRestStub): + 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': '/v1beta/{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 get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(DataprocMetastoreFederationRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy 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: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/backups/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/databases/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/databases/*/tables/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{resource=projects/*/locations/*/federations/*}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(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 = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(DataprocMetastoreFederationRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy 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: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/backups/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/databases/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/databases/*/tables/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/federations/*}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.loads(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) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(DataprocMetastoreFederationRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions 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: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/backups/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/databases/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/services/*/databases/*/tables/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/federations/*}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.loads(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) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(DataprocMetastoreFederationRestStub): + 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': '/v1beta/{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(DataprocMetastoreFederationRestStub): + 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': '/v1beta/{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(DataprocMetastoreFederationRestStub): + 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': '/v1beta/{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__=( + 'DataprocMetastoreFederationRestTransport', +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/types/__init__.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/types/__init__.py new file mode 100644 index 0000000..12c86eb --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/types/__init__.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .metastore import ( + AlterMetadataResourceLocationRequest, + AlterMetadataResourceLocationResponse, + AuxiliaryVersionConfig, + Backup, + CreateBackupRequest, + CreateMetadataImportRequest, + CreateServiceRequest, + DatabaseDumpSpec, + DataCatalogConfig, + DataplexConfig, + DeleteBackupRequest, + DeleteServiceRequest, + EncryptionConfig, + ExportMetadataRequest, + GetBackupRequest, + GetMetadataImportRequest, + GetServiceRequest, + HiveMetastoreConfig, + KerberosConfig, + Lake, + ListBackupsRequest, + ListBackupsResponse, + ListMetadataImportsRequest, + ListMetadataImportsResponse, + ListServicesRequest, + ListServicesResponse, + LocationMetadata, + MaintenanceWindow, + MetadataExport, + MetadataImport, + MetadataIntegration, + MetadataManagementActivity, + MoveTableToDatabaseRequest, + MoveTableToDatabaseResponse, + NetworkConfig, + OperationMetadata, + QueryMetadataRequest, + QueryMetadataResponse, + RemoveIamPolicyRequest, + RemoveIamPolicyResponse, + Restore, + RestoreServiceRequest, + Secret, + Service, + TelemetryConfig, + UpdateMetadataImportRequest, + UpdateServiceRequest, +) +from .metastore_federation import ( + BackendMetastore, + CreateFederationRequest, + DeleteFederationRequest, + Federation, + GetFederationRequest, + ListFederationsRequest, + ListFederationsResponse, + UpdateFederationRequest, +) + +__all__ = ( + 'AlterMetadataResourceLocationRequest', + 'AlterMetadataResourceLocationResponse', + 'AuxiliaryVersionConfig', + 'Backup', + 'CreateBackupRequest', + 'CreateMetadataImportRequest', + 'CreateServiceRequest', + 'DatabaseDumpSpec', + 'DataCatalogConfig', + 'DataplexConfig', + 'DeleteBackupRequest', + 'DeleteServiceRequest', + 'EncryptionConfig', + 'ExportMetadataRequest', + 'GetBackupRequest', + 'GetMetadataImportRequest', + 'GetServiceRequest', + 'HiveMetastoreConfig', + 'KerberosConfig', + 'Lake', + 'ListBackupsRequest', + 'ListBackupsResponse', + 'ListMetadataImportsRequest', + 'ListMetadataImportsResponse', + 'ListServicesRequest', + 'ListServicesResponse', + 'LocationMetadata', + 'MaintenanceWindow', + 'MetadataExport', + 'MetadataImport', + 'MetadataIntegration', + 'MetadataManagementActivity', + 'MoveTableToDatabaseRequest', + 'MoveTableToDatabaseResponse', + 'NetworkConfig', + 'OperationMetadata', + 'QueryMetadataRequest', + 'QueryMetadataResponse', + 'RemoveIamPolicyRequest', + 'RemoveIamPolicyResponse', + 'Restore', + 'RestoreServiceRequest', + 'Secret', + 'Service', + 'TelemetryConfig', + 'UpdateMetadataImportRequest', + 'UpdateServiceRequest', + 'BackendMetastore', + 'CreateFederationRequest', + 'DeleteFederationRequest', + 'Federation', + 'GetFederationRequest', + 'ListFederationsRequest', + 'ListFederationsResponse', + 'UpdateFederationRequest', +) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/types/metastore.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/types/metastore.py new file mode 100644 index 0000000..dab6a76 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/types/metastore.py @@ -0,0 +1,2257 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __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.protobuf import wrappers_pb2 # type: ignore +from google.type import dayofweek_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.metastore.v1beta', + manifest={ + 'Service', + 'MetadataIntegration', + 'DataCatalogConfig', + 'DataplexConfig', + 'Lake', + 'MaintenanceWindow', + 'HiveMetastoreConfig', + 'KerberosConfig', + 'Secret', + 'EncryptionConfig', + 'AuxiliaryVersionConfig', + 'NetworkConfig', + 'TelemetryConfig', + 'MetadataManagementActivity', + 'MetadataImport', + 'MetadataExport', + 'Backup', + 'Restore', + 'ListServicesRequest', + 'ListServicesResponse', + 'GetServiceRequest', + 'CreateServiceRequest', + 'UpdateServiceRequest', + 'DeleteServiceRequest', + 'ListMetadataImportsRequest', + 'ListMetadataImportsResponse', + 'GetMetadataImportRequest', + 'CreateMetadataImportRequest', + 'UpdateMetadataImportRequest', + 'ListBackupsRequest', + 'ListBackupsResponse', + 'GetBackupRequest', + 'CreateBackupRequest', + 'DeleteBackupRequest', + 'ExportMetadataRequest', + 'RestoreServiceRequest', + 'OperationMetadata', + 'LocationMetadata', + 'DatabaseDumpSpec', + 'RemoveIamPolicyRequest', + 'RemoveIamPolicyResponse', + 'QueryMetadataRequest', + 'QueryMetadataResponse', + 'MoveTableToDatabaseRequest', + 'MoveTableToDatabaseResponse', + 'AlterMetadataResourceLocationRequest', + 'AlterMetadataResourceLocationResponse', + }, +) + + +class Service(proto.Message): + r"""A managed metastore service that serves metadata queries. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + hive_metastore_config (google.cloud.metastore_v1beta.types.HiveMetastoreConfig): + Configuration information specific to running + Hive metastore software as the metastore + service. + + This field is a member of `oneof`_ ``metastore_config``. + name (str): + Immutable. The relative resource name of the metastore + service, in the following format: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metastore + service was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metastore + service was last updated. + labels (MutableMapping[str, str]): + User-defined labels for the metastore + service. + network (str): + Immutable. The relative resource name of the VPC network on + which the instance can be accessed. It is specified in the + following form: + + ``projects/{project_number}/global/networks/{network_id}``. + endpoint_uri (str): + Output only. The URI of the endpoint used to + access the metastore service. + port (int): + The TCP port at which the metastore service + is reached. Default: 9083. + state (google.cloud.metastore_v1beta.types.Service.State): + Output only. The current state of the + metastore service. + state_message (str): + Output only. Additional information about the + current state of the metastore service, if + available. + artifact_gcs_uri (str): + Output only. A Cloud Storage URI (starting with ``gs://``) + that specifies where artifacts related to the metastore + service are stored. + tier (google.cloud.metastore_v1beta.types.Service.Tier): + The tier of the service. + metadata_integration (google.cloud.metastore_v1beta.types.MetadataIntegration): + The setting that defines how metastore + metadata should be integrated with external + services and systems. + maintenance_window (google.cloud.metastore_v1beta.types.MaintenanceWindow): + The one hour maintenance window of the + metastore service. This specifies when the + service can be restarted for maintenance + purposes in UTC time. Maintenance window is not + needed for services with the SPANNER database + type. + uid (str): + Output only. The globally unique resource + identifier of the metastore service. + metadata_management_activity (google.cloud.metastore_v1beta.types.MetadataManagementActivity): + Output only. The metadata management + activities of the metastore service. + release_channel (google.cloud.metastore_v1beta.types.Service.ReleaseChannel): + Immutable. The release channel of the service. If + unspecified, defaults to ``STABLE``. + encryption_config (google.cloud.metastore_v1beta.types.EncryptionConfig): + Immutable. Information used to configure the + Dataproc Metastore service to encrypt customer + data at rest. Cannot be updated. + network_config (google.cloud.metastore_v1beta.types.NetworkConfig): + The configuration specifying the network + settings for the Dataproc Metastore service. + database_type (google.cloud.metastore_v1beta.types.Service.DatabaseType): + Immutable. The database type that the + Metastore service stores its data. + telemetry_config (google.cloud.metastore_v1beta.types.TelemetryConfig): + The configuration specifying telemetry settings for the + Dataproc Metastore service. If unspecified defaults to + ``JSON``. + """ + class State(proto.Enum): + r"""The current state of the metastore service. + + Values: + STATE_UNSPECIFIED (0): + The state of the metastore service is + unknown. + CREATING (1): + The metastore service is in the process of + being created. + ACTIVE (2): + The metastore service is running and ready to + serve queries. + SUSPENDING (3): + The metastore service is entering suspension. + Its query-serving availability may cease + unexpectedly. + SUSPENDED (4): + The metastore service is suspended and unable + to serve queries. + UPDATING (5): + The metastore service is being updated. It + remains usable but cannot accept additional + update requests or be deleted at this time. + DELETING (6): + The metastore service is undergoing deletion. + It cannot be used. + ERROR (7): + The metastore service has encountered an + error and cannot be used. The metastore service + should be deleted. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + SUSPENDING = 3 + SUSPENDED = 4 + UPDATING = 5 + DELETING = 6 + ERROR = 7 + + class Tier(proto.Enum): + r"""Available service tiers. + + Values: + TIER_UNSPECIFIED (0): + The tier is not set. + DEVELOPER (1): + The developer tier provides limited + scalability and no fault tolerance. Good for + low-cost proof-of-concept. + ENTERPRISE (3): + The enterprise tier provides multi-zone high + availability, and sufficient scalability for + enterprise-level Dataproc Metastore workloads. + """ + TIER_UNSPECIFIED = 0 + DEVELOPER = 1 + ENTERPRISE = 3 + + class ReleaseChannel(proto.Enum): + r"""Release channels bundle features of varying levels of + stability. Newer features may be introduced initially into less + stable release channels and can be automatically promoted into + more stable release channels. + + Values: + RELEASE_CHANNEL_UNSPECIFIED (0): + Release channel is not specified. + CANARY (1): + The ``CANARY`` release channel contains the newest features, + which may be unstable and subject to unresolved issues with + no known workarounds. Services using the ``CANARY`` release + channel are not subject to any SLAs. + STABLE (2): + The ``STABLE`` release channel contains features that are + considered stable and have been validated for production + use. + """ + RELEASE_CHANNEL_UNSPECIFIED = 0 + CANARY = 1 + STABLE = 2 + + class DatabaseType(proto.Enum): + r"""The backend database type for the metastore service. + + Values: + DATABASE_TYPE_UNSPECIFIED (0): + The DATABASE_TYPE is not set. + MYSQL (1): + MySQL is used to persist the metastore data. + SPANNER (2): + Spanner is used to persist the metastore + data. + """ + DATABASE_TYPE_UNSPECIFIED = 0 + MYSQL = 1 + SPANNER = 2 + + hive_metastore_config: 'HiveMetastoreConfig' = proto.Field( + proto.MESSAGE, + number=5, + oneof='metastore_config', + message='HiveMetastoreConfig', + ) + 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, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + network: str = proto.Field( + proto.STRING, + number=7, + ) + endpoint_uri: str = proto.Field( + proto.STRING, + number=8, + ) + port: int = proto.Field( + proto.INT32, + number=9, + ) + state: State = proto.Field( + proto.ENUM, + number=10, + enum=State, + ) + state_message: str = proto.Field( + proto.STRING, + number=11, + ) + artifact_gcs_uri: str = proto.Field( + proto.STRING, + number=12, + ) + tier: Tier = proto.Field( + proto.ENUM, + number=13, + enum=Tier, + ) + metadata_integration: 'MetadataIntegration' = proto.Field( + proto.MESSAGE, + number=14, + message='MetadataIntegration', + ) + maintenance_window: 'MaintenanceWindow' = proto.Field( + proto.MESSAGE, + number=15, + message='MaintenanceWindow', + ) + uid: str = proto.Field( + proto.STRING, + number=16, + ) + metadata_management_activity: 'MetadataManagementActivity' = proto.Field( + proto.MESSAGE, + number=17, + message='MetadataManagementActivity', + ) + release_channel: ReleaseChannel = proto.Field( + proto.ENUM, + number=19, + enum=ReleaseChannel, + ) + encryption_config: 'EncryptionConfig' = proto.Field( + proto.MESSAGE, + number=20, + message='EncryptionConfig', + ) + network_config: 'NetworkConfig' = proto.Field( + proto.MESSAGE, + number=21, + message='NetworkConfig', + ) + database_type: DatabaseType = proto.Field( + proto.ENUM, + number=22, + enum=DatabaseType, + ) + telemetry_config: 'TelemetryConfig' = proto.Field( + proto.MESSAGE, + number=23, + message='TelemetryConfig', + ) + + +class MetadataIntegration(proto.Message): + r"""Specifies how metastore metadata should be integrated with + external services. + + Attributes: + data_catalog_config (google.cloud.metastore_v1beta.types.DataCatalogConfig): + The integration config for the Data Catalog + service. + dataplex_config (google.cloud.metastore_v1beta.types.DataplexConfig): + The integration config for the Dataplex + service. + """ + + data_catalog_config: 'DataCatalogConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='DataCatalogConfig', + ) + dataplex_config: 'DataplexConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='DataplexConfig', + ) + + +class DataCatalogConfig(proto.Message): + r"""Specifies how metastore metadata should be integrated with + the Data Catalog service. + + Attributes: + enabled (bool): + Defines whether the metastore metadata should + be synced to Data Catalog. The default value is + to disable syncing metastore metadata to Data + Catalog. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class DataplexConfig(proto.Message): + r"""Specifies how metastore metadata should be integrated with + the Dataplex service. + + Attributes: + lake_resources (MutableMapping[str, google.cloud.metastore_v1beta.types.Lake]): + A reference to the Lake resources that this metastore + service is attached to. The key is the lake resource name. + Example: + ``projects/{project_number}/locations/{location_id}/lakes/{lake_id}``. + """ + + lake_resources: MutableMapping[str, 'Lake'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message='Lake', + ) + + +class Lake(proto.Message): + r"""Represents a Lake resource + + Attributes: + name (str): + The Lake resource name. Example: + ``projects/{project_number}/locations/{location_id}/lakes/{lake_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class MaintenanceWindow(proto.Message): + r"""Maintenance window. This specifies when Dataproc Metastore + may perform system maintenance operation to the service. + + Attributes: + hour_of_day (google.protobuf.wrappers_pb2.Int32Value): + The hour of day (0-23) when the window + starts. + day_of_week (google.type.dayofweek_pb2.DayOfWeek): + The day of week, when the window starts. + """ + + hour_of_day: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=1, + message=wrappers_pb2.Int32Value, + ) + day_of_week: dayofweek_pb2.DayOfWeek = proto.Field( + proto.ENUM, + number=2, + enum=dayofweek_pb2.DayOfWeek, + ) + + +class HiveMetastoreConfig(proto.Message): + r"""Specifies configuration information specific to running Hive + metastore software as the metastore service. + + Attributes: + version (str): + Immutable. The Hive metastore schema version. + config_overrides (MutableMapping[str, str]): + A mapping of Hive metastore configuration key-value pairs to + apply to the Hive metastore (configured in + ``hive-site.xml``). The mappings override system defaults + (some keys cannot be overridden). These overrides are also + applied to auxiliary versions and can be further customized + in the auxiliary version's ``AuxiliaryVersionConfig``. + kerberos_config (google.cloud.metastore_v1beta.types.KerberosConfig): + Information used to configure the Hive metastore service as + a service principal in a Kerberos realm. To disable + Kerberos, use the ``UpdateService`` method and specify this + field's path (``hive_metastore_config.kerberos_config``) in + the request's ``update_mask`` while omitting this field from + the request's ``service``. + endpoint_protocol (google.cloud.metastore_v1beta.types.HiveMetastoreConfig.EndpointProtocol): + The protocol to use for the metastore service endpoint. If + unspecified, defaults to ``THRIFT``. + auxiliary_versions (MutableMapping[str, google.cloud.metastore_v1beta.types.AuxiliaryVersionConfig]): + A mapping of Hive metastore version to the auxiliary version + configuration. When specified, a secondary Hive metastore + service is created along with the primary service. All + auxiliary versions must be less than the service's primary + version. The key is the auxiliary service name and it must + match the regular expression `a-z <[-a-z0-9]*[a-z0-9]>`__?. + This means that the first character must be a lowercase + letter, and all the following characters must be hyphens, + lowercase letters, or digits, except the last character, + which cannot be a hyphen. + """ + class EndpointProtocol(proto.Enum): + r"""Protocols available for serving the metastore service + endpoint. + + Values: + ENDPOINT_PROTOCOL_UNSPECIFIED (0): + The protocol is not set. + THRIFT (1): + Use the legacy Apache Thrift protocol for the + metastore service endpoint. + GRPC (2): + Use the modernized gRPC protocol for the + metastore service endpoint. + """ + ENDPOINT_PROTOCOL_UNSPECIFIED = 0 + THRIFT = 1 + GRPC = 2 + + version: str = proto.Field( + proto.STRING, + number=1, + ) + config_overrides: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + kerberos_config: 'KerberosConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='KerberosConfig', + ) + endpoint_protocol: EndpointProtocol = proto.Field( + proto.ENUM, + number=4, + enum=EndpointProtocol, + ) + auxiliary_versions: MutableMapping[str, 'AuxiliaryVersionConfig'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=5, + message='AuxiliaryVersionConfig', + ) + + +class KerberosConfig(proto.Message): + r"""Configuration information for a Kerberos principal. + + Attributes: + keytab (google.cloud.metastore_v1beta.types.Secret): + A Kerberos keytab file that can be used to + authenticate a service principal with a Kerberos + Key Distribution Center (KDC). + principal (str): + A Kerberos principal that exists in the both the keytab the + KDC to authenticate as. A typical principal is of the form + ``primary/instance@REALM``, but there is no exact format. + krb5_config_gcs_uri (str): + A Cloud Storage URI that specifies the path to a krb5.conf + file. It is of the form + ``gs://{bucket_name}/path/to/krb5.conf``, although the file + does not need to be named krb5.conf explicitly. + """ + + keytab: 'Secret' = proto.Field( + proto.MESSAGE, + number=1, + message='Secret', + ) + principal: str = proto.Field( + proto.STRING, + number=2, + ) + krb5_config_gcs_uri: str = proto.Field( + proto.STRING, + number=3, + ) + + +class Secret(proto.Message): + r"""A securely stored value. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_secret (str): + The relative resource name of a Secret Manager secret + version, in the following form: + + ``projects/{project_number}/secrets/{secret_id}/versions/{version_id}``. + + This field is a member of `oneof`_ ``value``. + """ + + cloud_secret: str = proto.Field( + proto.STRING, + number=2, + oneof='value', + ) + + +class EncryptionConfig(proto.Message): + r"""Encryption settings for the service. + + Attributes: + kms_key (str): + The fully qualified customer provided Cloud KMS key name to + use for customer data encryption, in the following form: + + ``projects/{project_number}/locations/{location_id}/keyRings/{key_ring_id}/cryptoKeys/{crypto_key_id}``. + """ + + kms_key: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AuxiliaryVersionConfig(proto.Message): + r"""Configuration information for the auxiliary service versions. + + Attributes: + version (str): + The Hive metastore version of the auxiliary + service. It must be less than the primary Hive + metastore service's version. + config_overrides (MutableMapping[str, str]): + A mapping of Hive metastore configuration key-value pairs to + apply to the auxiliary Hive metastore (configured in + ``hive-site.xml``) in addition to the primary version's + overrides. If keys are present in both the auxiliary + version's overrides and the primary version's overrides, the + value from the auxiliary version's overrides takes + precedence. + network_config (google.cloud.metastore_v1beta.types.NetworkConfig): + Output only. The network configuration + contains the endpoint URI(s) of the auxiliary + Hive metastore service. + """ + + version: str = proto.Field( + proto.STRING, + number=1, + ) + config_overrides: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + network_config: 'NetworkConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='NetworkConfig', + ) + + +class NetworkConfig(proto.Message): + r"""Network configuration for the Dataproc Metastore service. + + Attributes: + consumers (MutableSequence[google.cloud.metastore_v1beta.types.NetworkConfig.Consumer]): + Immutable. The consumer-side network + configuration for the Dataproc Metastore + instance. + """ + + class Consumer(proto.Message): + r"""Contains information of the customer's network + configurations. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + subnetwork (str): + Immutable. The subnetwork of the customer project from which + an IP address is reserved and used as the Dataproc Metastore + service's endpoint. It is accessible to hosts in the subnet + and to all hosts in a subnet in the same region and same + network. There must be at least one IP address available in + the subnet's primary range. The subnet is specified in the + following form: + + ``projects/{project_number}/regions/{region_id}/subnetworks/{subnetwork_id}`` + + This field is a member of `oneof`_ ``vpc_resource``. + endpoint_uri (str): + Output only. The URI of the endpoint used to + access the metastore service. + """ + + subnetwork: str = proto.Field( + proto.STRING, + number=1, + oneof='vpc_resource', + ) + endpoint_uri: str = proto.Field( + proto.STRING, + number=3, + ) + + consumers: MutableSequence[Consumer] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Consumer, + ) + + +class TelemetryConfig(proto.Message): + r"""Telemetry Configuration for the Dataproc Metastore service. + + Attributes: + log_format (google.cloud.metastore_v1beta.types.TelemetryConfig.LogFormat): + The output format of the Dataproc Metastore + service's logs. + """ + class LogFormat(proto.Enum): + r""" + + Values: + LOG_FORMAT_UNSPECIFIED (0): + The LOG_FORMAT is not set. + LEGACY (1): + Logging output uses the legacy ``textPayload`` format. + JSON (2): + Logging output uses the ``jsonPayload`` format. + """ + LOG_FORMAT_UNSPECIFIED = 0 + LEGACY = 1 + JSON = 2 + + log_format: LogFormat = proto.Field( + proto.ENUM, + number=1, + enum=LogFormat, + ) + + +class MetadataManagementActivity(proto.Message): + r"""The metadata management activities of the metastore service. + + Attributes: + metadata_exports (MutableSequence[google.cloud.metastore_v1beta.types.MetadataExport]): + Output only. The latest metadata exports of + the metastore service. + restores (MutableSequence[google.cloud.metastore_v1beta.types.Restore]): + Output only. The latest restores of the + metastore service. + """ + + metadata_exports: MutableSequence['MetadataExport'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='MetadataExport', + ) + restores: MutableSequence['Restore'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Restore', + ) + + +class MetadataImport(proto.Message): + r"""A metastore resource that imports metadata. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + database_dump (google.cloud.metastore_v1beta.types.MetadataImport.DatabaseDump): + Immutable. A database dump from a + pre-existing metastore's database. + + This field is a member of `oneof`_ ``metadata``. + name (str): + Immutable. The relative resource name of the metadata + import, of the form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports/{metadata_import_id}``. + description (str): + The description of the metadata import. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metadata + import was started. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metadata + import was last updated. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metadata + import finished. + state (google.cloud.metastore_v1beta.types.MetadataImport.State): + Output only. The current state of the + metadata import. + """ + class State(proto.Enum): + r"""The current state of the metadata import. + + Values: + STATE_UNSPECIFIED (0): + The state of the metadata import is unknown. + RUNNING (1): + The metadata import is running. + SUCCEEDED (2): + The metadata import completed successfully. + UPDATING (3): + The metadata import is being updated. + FAILED (4): + The metadata import failed, and attempted + metadata changes were rolled back. + """ + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + UPDATING = 3 + FAILED = 4 + + class DatabaseDump(proto.Message): + r"""A specification of the location of and metadata about a + database dump from a relational database management system. + + Attributes: + database_type (google.cloud.metastore_v1beta.types.MetadataImport.DatabaseDump.DatabaseType): + The type of the database. + gcs_uri (str): + A Cloud Storage object or folder URI that specifies the + source from which to import metadata. It must begin with + ``gs://``. + source_database (str): + The name of the source database. + type_ (google.cloud.metastore_v1beta.types.DatabaseDumpSpec.Type): + Optional. The type of the database dump. If unspecified, + defaults to ``MYSQL``. + """ + class DatabaseType(proto.Enum): + r"""The type of the database. + + Values: + DATABASE_TYPE_UNSPECIFIED (0): + The type of the source database is unknown. + MYSQL (1): + The type of the source database is MySQL. + """ + DATABASE_TYPE_UNSPECIFIED = 0 + MYSQL = 1 + + database_type: 'MetadataImport.DatabaseDump.DatabaseType' = proto.Field( + proto.ENUM, + number=1, + enum='MetadataImport.DatabaseDump.DatabaseType', + ) + gcs_uri: str = proto.Field( + proto.STRING, + number=2, + ) + source_database: str = proto.Field( + proto.STRING, + number=3, + ) + type_: 'DatabaseDumpSpec.Type' = proto.Field( + proto.ENUM, + number=4, + enum='DatabaseDumpSpec.Type', + ) + + database_dump: DatabaseDump = proto.Field( + proto.MESSAGE, + number=6, + oneof='metadata', + message=DatabaseDump, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + state: State = proto.Field( + proto.ENUM, + number=5, + enum=State, + ) + + +class MetadataExport(proto.Message): + r"""The details of a metadata export operation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + destination_gcs_uri (str): + Output only. A Cloud Storage URI of a folder that metadata + are exported to, in the form of + ``gs:////``, + where ```` is automatically generated. + + This field is a member of `oneof`_ ``destination``. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the export + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the export ended. + state (google.cloud.metastore_v1beta.types.MetadataExport.State): + Output only. The current state of the export. + database_dump_type (google.cloud.metastore_v1beta.types.DatabaseDumpSpec.Type): + Output only. The type of the database dump. + """ + class State(proto.Enum): + r"""The current state of the metadata export. + + Values: + STATE_UNSPECIFIED (0): + The state of the metadata export is unknown. + RUNNING (1): + The metadata export is running. + SUCCEEDED (2): + The metadata export completed successfully. + FAILED (3): + The metadata export failed. + CANCELLED (4): + The metadata export is cancelled. + """ + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + FAILED = 3 + CANCELLED = 4 + + destination_gcs_uri: str = proto.Field( + proto.STRING, + number=4, + oneof='destination', + ) + start_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, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + database_dump_type: 'DatabaseDumpSpec.Type' = proto.Field( + proto.ENUM, + number=5, + enum='DatabaseDumpSpec.Type', + ) + + +class Backup(proto.Message): + r"""The details of a backup resource. + + Attributes: + name (str): + Immutable. The relative resource name of the backup, in the + following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the backup was + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the backup + finished creating. + state (google.cloud.metastore_v1beta.types.Backup.State): + Output only. The current state of the backup. + service_revision (google.cloud.metastore_v1beta.types.Service): + Output only. The revision of the service at + the time of backup. + description (str): + The description of the backup. + restoring_services (MutableSequence[str]): + Output only. Services that are restoring from + the backup. + """ + class State(proto.Enum): + r"""The current state of the backup. + + Values: + STATE_UNSPECIFIED (0): + The state of the backup is unknown. + CREATING (1): + The backup is being created. + DELETING (2): + The backup is being deleted. + ACTIVE (3): + The backup is active and ready to use. + FAILED (4): + The backup failed. + RESTORING (5): + The backup is being restored. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + DELETING = 2 + ACTIVE = 3 + FAILED = 4 + RESTORING = 5 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + service_revision: 'Service' = proto.Field( + proto.MESSAGE, + number=5, + message='Service', + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + restoring_services: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + +class Restore(proto.Message): + r"""The details of a metadata restore operation. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the restore + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the restore ended. + state (google.cloud.metastore_v1beta.types.Restore.State): + Output only. The current state of the + restore. + backup (str): + Output only. The relative resource name of the metastore + service backup to restore from, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + type_ (google.cloud.metastore_v1beta.types.Restore.RestoreType): + Output only. The type of restore. + details (str): + Output only. The restore details containing + the revision of the service to be restored to, + in format of JSON. + """ + class State(proto.Enum): + r"""The current state of the restore. + + Values: + STATE_UNSPECIFIED (0): + The state of the metadata restore is unknown. + RUNNING (1): + The metadata restore is running. + SUCCEEDED (2): + The metadata restore completed successfully. + FAILED (3): + The metadata restore failed. + CANCELLED (4): + The metadata restore is cancelled. + """ + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + FAILED = 3 + CANCELLED = 4 + + class RestoreType(proto.Enum): + r"""The type of restore. If unspecified, defaults to ``METADATA_ONLY``. + + Values: + RESTORE_TYPE_UNSPECIFIED (0): + The restore type is unknown. + FULL (1): + The service's metadata and configuration are + restored. + METADATA_ONLY (2): + Only the service's metadata is restored. + """ + RESTORE_TYPE_UNSPECIFIED = 0 + FULL = 1 + METADATA_ONLY = 2 + + start_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, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + backup: str = proto.Field( + proto.STRING, + number=4, + ) + type_: RestoreType = proto.Field( + proto.ENUM, + number=5, + enum=RestoreType, + ) + details: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ListServicesRequest(proto.Message): + r"""Request message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1beta.DataprocMetastore.ListServices]. + + Attributes: + parent (str): + Required. The relative resource name of the location of + metastore services to list, in the following form: + + ``projects/{project_number}/locations/{location_id}``. + page_size (int): + Optional. The maximum number of services to + return. The response may contain less than the + maximum number. If unspecified, no more than 500 + services are returned. The maximum value is + 1000; values above 1000 are changed to 1000. + page_token (str): + Optional. A page token, received from a previous + [DataprocMetastore.ListServices][google.cloud.metastore.v1beta.DataprocMetastore.ListServices] + call. Provide this token to retrieve the subsequent page. + + To retrieve the first page, supply an empty page token. + + When paginating, other parameters provided to + [DataprocMetastore.ListServices][google.cloud.metastore.v1beta.DataprocMetastore.ListServices] + must match the call that provided the page token. + filter (str): + Optional. The filter to apply to list + results. + order_by (str): + Optional. Specify the ordering of results as described in + `Sorting + Order `__. + If not specified, the results will be sorted in the default + order. + """ + + 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 ListServicesResponse(proto.Message): + r"""Response message for + [DataprocMetastore.ListServices][google.cloud.metastore.v1beta.DataprocMetastore.ListServices]. + + Attributes: + services (MutableSequence[google.cloud.metastore_v1beta.types.Service]): + The services in the specified location. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + services: MutableSequence['Service'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Service', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetServiceRequest(proto.Message): + r"""Request message for + [DataprocMetastore.GetService][google.cloud.metastore.v1beta.DataprocMetastore.GetService]. + + Attributes: + name (str): + Required. The relative resource name of the metastore + service to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateServiceRequest(proto.Message): + r"""Request message for + [DataprocMetastore.CreateService][google.cloud.metastore.v1beta.DataprocMetastore.CreateService]. + + Attributes: + parent (str): + Required. The relative resource name of the location in + which to create a metastore service, in the following form: + + ``projects/{project_number}/locations/{location_id}``. + service_id (str): + Required. The ID of the metastore service, + which is used as the final component of the + metastore service's name. + This value must be between 2 and 63 characters + long inclusive, begin with a letter, end with a + letter or number, and consist of alpha-numeric + ASCII characters or hyphens. + service (google.cloud.metastore_v1beta.types.Service): + Required. The Metastore service to create. The ``name`` + field is ignored. The ID of the created metastore service + must be provided in the request's ``service_id`` field. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + service_id: str = proto.Field( + proto.STRING, + number=2, + ) + service: 'Service' = proto.Field( + proto.MESSAGE, + number=3, + message='Service', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateServiceRequest(proto.Message): + r"""Request message for + [DataprocMetastore.UpdateService][google.cloud.metastore.v1beta.DataprocMetastore.UpdateService]. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask used to specify the fields to be + overwritten in the metastore service resource by the update. + Fields specified in the ``update_mask`` are relative to the + resource (not to the full request). A field is overwritten + if it is in the mask. + service (google.cloud.metastore_v1beta.types.Service): + Required. The metastore service to update. The server only + merges fields in the service if they are specified in + ``update_mask``. + + The metastore service's ``name`` field is used to identify + the metastore service to be updated. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + service: 'Service' = proto.Field( + proto.MESSAGE, + number=2, + message='Service', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteServiceRequest(proto.Message): + r"""Request message for + [DataprocMetastore.DeleteService][google.cloud.metastore.v1beta.DataprocMetastore.DeleteService]. + + Attributes: + name (str): + Required. The relative resource name of the metastore + service to delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListMetadataImportsRequest(proto.Message): + r"""Request message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1beta.DataprocMetastore.ListMetadataImports]. + + Attributes: + parent (str): + Required. The relative resource name of the service whose + metadata imports to list, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports``. + page_size (int): + Optional. The maximum number of imports to + return. The response may contain less than the + maximum number. If unspecified, no more than 500 + imports are returned. The maximum value is 1000; + values above 1000 are changed to 1000. + page_token (str): + Optional. A page token, received from a previous + [DataprocMetastore.ListServices][google.cloud.metastore.v1beta.DataprocMetastore.ListServices] + call. Provide this token to retrieve the subsequent page. + + To retrieve the first page, supply an empty page token. + + When paginating, other parameters provided to + [DataprocMetastore.ListServices][google.cloud.metastore.v1beta.DataprocMetastore.ListServices] + must match the call that provided the page token. + filter (str): + Optional. The filter to apply to list + results. + order_by (str): + Optional. Specify the ordering of results as described in + `Sorting + Order `__. + If not specified, the results will be sorted in the default + order. + """ + + 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 ListMetadataImportsResponse(proto.Message): + r"""Response message for + [DataprocMetastore.ListMetadataImports][google.cloud.metastore.v1beta.DataprocMetastore.ListMetadataImports]. + + Attributes: + metadata_imports (MutableSequence[google.cloud.metastore_v1beta.types.MetadataImport]): + The imports in the specified service. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + metadata_imports: MutableSequence['MetadataImport'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='MetadataImport', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetMetadataImportRequest(proto.Message): + r"""Request message for + [DataprocMetastore.GetMetadataImport][google.cloud.metastore.v1beta.DataprocMetastore.GetMetadataImport]. + + Attributes: + name (str): + Required. The relative resource name of the metadata import + to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports/{import_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateMetadataImportRequest(proto.Message): + r"""Request message for + [DataprocMetastore.CreateMetadataImport][google.cloud.metastore.v1beta.DataprocMetastore.CreateMetadataImport]. + + Attributes: + parent (str): + Required. The relative resource name of the service in which + to create a metastore import, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + metadata_import_id (str): + Required. The ID of the metadata import, + which is used as the final component of the + metadata import's name. + This value must be between 1 and 64 characters + long, begin with a letter, end with a letter or + number, and consist of alpha-numeric ASCII + characters or hyphens. + metadata_import (google.cloud.metastore_v1beta.types.MetadataImport): + Required. The metadata import to create. The ``name`` field + is ignored. The ID of the created metadata import must be + provided in the request's ``metadata_import_id`` field. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + metadata_import_id: str = proto.Field( + proto.STRING, + number=2, + ) + metadata_import: 'MetadataImport' = proto.Field( + proto.MESSAGE, + number=3, + message='MetadataImport', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateMetadataImportRequest(proto.Message): + r"""Request message for + [DataprocMetastore.UpdateMetadataImport][google.cloud.metastore.v1beta.DataprocMetastore.UpdateMetadataImport]. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask used to specify the fields to be + overwritten in the metadata import resource by the update. + Fields specified in the ``update_mask`` are relative to the + resource (not to the full request). A field is overwritten + if it is in the mask. + metadata_import (google.cloud.metastore_v1beta.types.MetadataImport): + Required. The metadata import to update. The server only + merges fields in the import if they are specified in + ``update_mask``. + + The metadata import's ``name`` field is used to identify the + metastore import to be updated. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + metadata_import: 'MetadataImport' = proto.Field( + proto.MESSAGE, + number=2, + message='MetadataImport', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListBackupsRequest(proto.Message): + r"""Request message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1beta.DataprocMetastore.ListBackups]. + + Attributes: + parent (str): + Required. The relative resource name of the service whose + backups to list, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups``. + page_size (int): + Optional. The maximum number of backups to + return. The response may contain less than the + maximum number. If unspecified, no more than 500 + backups are returned. The maximum value is 1000; + values above 1000 are changed to 1000. + page_token (str): + Optional. A page token, received from a previous + [DataprocMetastore.ListBackups][google.cloud.metastore.v1beta.DataprocMetastore.ListBackups] + call. Provide this token to retrieve the subsequent page. + + To retrieve the first page, supply an empty page token. + + When paginating, other parameters provided to + [DataprocMetastore.ListBackups][google.cloud.metastore.v1beta.DataprocMetastore.ListBackups] + must match the call that provided the page token. + filter (str): + Optional. The filter to apply to list + results. + order_by (str): + Optional. Specify the ordering of results as described in + `Sorting + Order `__. + If not specified, the results will be sorted in the default + order. + """ + + 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 ListBackupsResponse(proto.Message): + r"""Response message for + [DataprocMetastore.ListBackups][google.cloud.metastore.v1beta.DataprocMetastore.ListBackups]. + + Attributes: + backups (MutableSequence[google.cloud.metastore_v1beta.types.Backup]): + The backups of the specified service. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + backups: MutableSequence['Backup'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Backup', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetBackupRequest(proto.Message): + r"""Request message for + [DataprocMetastore.GetBackup][google.cloud.metastore.v1beta.DataprocMetastore.GetBackup]. + + Attributes: + name (str): + Required. The relative resource name of the backup to + retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateBackupRequest(proto.Message): + r"""Request message for + [DataprocMetastore.CreateBackup][google.cloud.metastore.v1beta.DataprocMetastore.CreateBackup]. + + Attributes: + parent (str): + Required. The relative resource name of the service in which + to create a backup of the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}``. + backup_id (str): + Required. The ID of the backup, which is used + as the final component of the backup's name. + + This value must be between 1 and 64 characters + long, begin with a letter, end with a letter or + number, and consist of alpha-numeric ASCII + characters or hyphens. + backup (google.cloud.metastore_v1beta.types.Backup): + Required. The backup to create. The ``name`` field is + ignored. The ID of the created backup must be provided in + the request's ``backup_id`` field. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + backup_id: str = proto.Field( + proto.STRING, + number=2, + ) + backup: 'Backup' = proto.Field( + proto.MESSAGE, + number=3, + message='Backup', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class DeleteBackupRequest(proto.Message): + r"""Request message for + [DataprocMetastore.DeleteBackup][google.cloud.metastore.v1beta.DataprocMetastore.DeleteBackup]. + + Attributes: + name (str): + Required. The relative resource name of the backup to + delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ExportMetadataRequest(proto.Message): + r"""Request message for + [DataprocMetastore.ExportMetadata][google.cloud.metastore.v1beta.DataprocMetastore.ExportMetadata]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + destination_gcs_folder (str): + A Cloud Storage URI of a folder, in the format + ``gs:///``. A sub-folder + ```` containing exported files will be + created below it. + + This field is a member of `oneof`_ ``destination``. + service (str): + Required. The relative resource name of the metastore + service to run export, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}``. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__. + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + database_dump_type (google.cloud.metastore_v1beta.types.DatabaseDumpSpec.Type): + Optional. The type of the database dump. If unspecified, + defaults to ``MYSQL``. + """ + + destination_gcs_folder: str = proto.Field( + proto.STRING, + number=2, + oneof='destination', + ) + service: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + database_dump_type: 'DatabaseDumpSpec.Type' = proto.Field( + proto.ENUM, + number=4, + enum='DatabaseDumpSpec.Type', + ) + + +class RestoreServiceRequest(proto.Message): + r"""Request message for [DataprocMetastore.Restore][]. + + Attributes: + service (str): + Required. The relative resource name of the metastore + service to run restore, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}``. + backup (str): + Required. The relative resource name of the metastore + service backup to restore from, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}/backups/{backup_id}``. + restore_type (google.cloud.metastore_v1beta.types.Restore.RestoreType): + Optional. The type of restore. If unspecified, defaults to + ``METADATA_ONLY``. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__. + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + service: str = proto.Field( + proto.STRING, + number=1, + ) + backup: str = proto.Field( + proto.STRING, + number=2, + ) + restore_type: 'Restore.RestoreType' = proto.Field( + proto.ENUM, + number=3, + enum='Restore.RestoreType', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of a 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 caller has requested + cancellation of the operation. Operations that have + successfully been cancelled 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 LocationMetadata(proto.Message): + r"""Metadata about the service in a location. + + Attributes: + supported_hive_metastore_versions (MutableSequence[google.cloud.metastore_v1beta.types.LocationMetadata.HiveMetastoreVersion]): + The versions of Hive Metastore that can be used when + creating a new metastore service in this location. The + server guarantees that exactly one ``HiveMetastoreVersion`` + in the list will set ``is_default``. + """ + + class HiveMetastoreVersion(proto.Message): + r"""A specification of a supported version of the Hive Metastore + software. + + Attributes: + version (str): + The semantic version of the Hive Metastore + software. + is_default (bool): + Whether ``version`` will be chosen by the server if a + metastore service is created with a ``HiveMetastoreConfig`` + that omits the ``version``. + """ + + version: str = proto.Field( + proto.STRING, + number=1, + ) + is_default: bool = proto.Field( + proto.BOOL, + number=2, + ) + + supported_hive_metastore_versions: MutableSequence[HiveMetastoreVersion] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=HiveMetastoreVersion, + ) + + +class DatabaseDumpSpec(proto.Message): + r"""The specification of database dump to import from or export + to. + + """ + class Type(proto.Enum): + r"""The type of the database dump. + + Values: + TYPE_UNSPECIFIED (0): + The type of the database dump is unknown. + MYSQL (1): + Database dump is a MySQL dump file. + AVRO (2): + Database dump contains Avro files. + """ + TYPE_UNSPECIFIED = 0 + MYSQL = 1 + AVRO = 2 + + +class RemoveIamPolicyRequest(proto.Message): + r"""Request message for + [DataprocMetastore.RemoveIamPolicy][google.cloud.metastore.v1beta.DataprocMetastore.RemoveIamPolicy]. + + Attributes: + resource (str): + Required. The relative resource name of the dataplane + resource to remove IAM policy, in the following form: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}/databases/{database_id}`` + or + ``projects/{project_id}/locations/{location_id}/services/{service_id}/databases/{database_id}/tables/{table_id}``. + asynchronous (bool): + Optional. Removes IAM policy attached to + database or table asynchronously when it is set. + The default is false. + """ + + resource: str = proto.Field( + proto.STRING, + number=1, + ) + asynchronous: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class RemoveIamPolicyResponse(proto.Message): + r"""Response message for + [DataprocMetastore.RemoveIamPolicy][google.cloud.metastore.v1beta.DataprocMetastore.RemoveIamPolicy]. + + Attributes: + success (bool): + True if the policy is successfully removed. + """ + + success: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +class QueryMetadataRequest(proto.Message): + r"""Request message for + [DataprocMetastore.QueryMetadata][google.cloud.metastore.v1beta.DataprocMetastore.QueryMetadata]. + + Attributes: + service (str): + Required. The relative resource name of the metastore + service to query metadata, in the following format: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}``. + query (str): + Required. A read-only SQL query to execute + against the metadata database. The query cannot + change or mutate the data. + """ + + service: str = proto.Field( + proto.STRING, + number=1, + ) + query: str = proto.Field( + proto.STRING, + number=2, + ) + + +class QueryMetadataResponse(proto.Message): + r"""Response message for + [DataprocMetastore.QueryMetadata][google.cloud.metastore.v1beta.DataprocMetastore.QueryMetadata]. + + Attributes: + result_manifest_uri (str): + The manifest URI is link to a JSON instance + in Cloud Storage. This instance manifests + immediately along with QueryMetadataResponse. + The content of the URI is not retriable until + the long-running operation query against the + metadata finishes. + """ + + result_manifest_uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +class MoveTableToDatabaseRequest(proto.Message): + r"""Request message for + [DataprocMetastore.MoveTableToDatabase][google.cloud.metastore.v1beta.DataprocMetastore.MoveTableToDatabase]. + + Attributes: + service (str): + Required. The relative resource name of the metastore + service to mutate metadata, in the following format: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}``. + table_name (str): + Required. The name of the table to be moved. + db_name (str): + Required. The name of the database where the + table resides. + destination_db_name (str): + Required. The name of the database where the + table should be moved. + """ + + service: str = proto.Field( + proto.STRING, + number=1, + ) + table_name: str = proto.Field( + proto.STRING, + number=2, + ) + db_name: str = proto.Field( + proto.STRING, + number=3, + ) + destination_db_name: str = proto.Field( + proto.STRING, + number=4, + ) + + +class MoveTableToDatabaseResponse(proto.Message): + r"""Response message for + [DataprocMetastore.MoveTableToDatabase][google.cloud.metastore.v1beta.DataprocMetastore.MoveTableToDatabase]. + + """ + + +class AlterMetadataResourceLocationRequest(proto.Message): + r"""Request message for + [DataprocMetastore.AlterMetadataResourceLocation][google.cloud.metastore.v1beta.DataprocMetastore.AlterMetadataResourceLocation]. + + Attributes: + service (str): + Required. The relative resource name of the metastore + service to mutate metadata, in the following format: + + ``projects/{project_id}/locations/{location_id}/services/{service_id}``. + resource_name (str): + Required. The relative metadata resource name in the + following format. + + ``databases/{database_id}`` or + ``databases/{database_id}/tables/{table_id}`` or + ``databases/{database_id}/tables/{table_id}/partitions/{partition_id}`` + location_uri (str): + Required. The new location URI for the + metadata resource. + """ + + service: str = proto.Field( + proto.STRING, + number=1, + ) + resource_name: str = proto.Field( + proto.STRING, + number=2, + ) + location_uri: str = proto.Field( + proto.STRING, + number=3, + ) + + +class AlterMetadataResourceLocationResponse(proto.Message): + r"""Response message for + [DataprocMetastore.AlterMetadataResourceLocation][google.cloud.metastore.v1beta.DataprocMetastore.AlterMetadataResourceLocation]. + + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/types/metastore_federation.py b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/types/metastore_federation.py new file mode 100644 index 0000000..e1f6255 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/metastore_v1beta/types/metastore_federation.py @@ -0,0 +1,466 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.metastore.v1beta', + manifest={ + 'Federation', + 'BackendMetastore', + 'ListFederationsRequest', + 'ListFederationsResponse', + 'GetFederationRequest', + 'CreateFederationRequest', + 'UpdateFederationRequest', + 'DeleteFederationRequest', + }, +) + + +class Federation(proto.Message): + r"""Represents a federation of multiple backend metastores. + + Attributes: + name (str): + Immutable. The relative resource name of the federation, of + the form: + projects/{project_number}/locations/{location_id}/federations/{federation_id}`. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metastore + federation was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the metastore + federation was last updated. + labels (MutableMapping[str, str]): + User-defined labels for the metastore + federation. + version (str): + Immutable. The Apache Hive metastore version + of the federation. All backend metastore + versions must be compatible with the federation + version. + backend_metastores (MutableMapping[int, google.cloud.metastore_v1beta.types.BackendMetastore]): + A map from ``BackendMetastore`` rank to + ``BackendMetastore``\ s from which the federation service + serves metadata at query time. The map key represents the + order in which ``BackendMetastore``\ s should be evaluated + to resolve database names at query time and should be + greater than or equal to zero. A ``BackendMetastore`` with a + lower number will be evaluated before a ``BackendMetastore`` + with a higher number. + endpoint_uri (str): + Output only. The federation endpoint. + state (google.cloud.metastore_v1beta.types.Federation.State): + Output only. The current state of the + federation. + state_message (str): + Output only. Additional information about the + current state of the metastore federation, if + available. + uid (str): + Output only. The globally unique resource + identifier of the metastore federation. + """ + class State(proto.Enum): + r"""The current state of the federation. + + Values: + STATE_UNSPECIFIED (0): + The state of the metastore federation is + unknown. + CREATING (1): + The metastore federation is in the process of + being created. + ACTIVE (2): + The metastore federation is running and ready + to serve queries. + UPDATING (3): + The metastore federation is being updated. It + remains usable but cannot accept additional + update requests or be deleted at this time. + DELETING (4): + The metastore federation is undergoing + deletion. It cannot be used. + ERROR (5): + The metastore federation has encountered an + error and cannot be used. The metastore + federation should be deleted. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + UPDATING = 3 + DELETING = 4 + ERROR = 5 + + 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, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + version: str = proto.Field( + proto.STRING, + number=5, + ) + backend_metastores: MutableMapping[int, 'BackendMetastore'] = proto.MapField( + proto.INT32, + proto.MESSAGE, + number=6, + message='BackendMetastore', + ) + endpoint_uri: str = proto.Field( + proto.STRING, + number=7, + ) + state: State = proto.Field( + proto.ENUM, + number=8, + enum=State, + ) + state_message: str = proto.Field( + proto.STRING, + number=9, + ) + uid: str = proto.Field( + proto.STRING, + number=10, + ) + + +class BackendMetastore(proto.Message): + r"""Represents a backend metastore for the federation. + + Attributes: + name (str): + The relative resource name of the metastore that is being + federated. The formats of the relative resource names for + the currently supported metastores are listed below: + + - Dataplex + + - ``projects/{project_id}/locations/{location}/lakes/{lake_id}`` + + - BigQuery + + - ``projects/{project_id}`` + + - Dataproc Metastore + + - ``projects/{project_id}/locations/{location}/services/{service_id}`` + metastore_type (google.cloud.metastore_v1beta.types.BackendMetastore.MetastoreType): + The type of the backend metastore. + """ + class MetastoreType(proto.Enum): + r"""The type of the backend metastore. + + Values: + METASTORE_TYPE_UNSPECIFIED (0): + The metastore type is not set. + BIGQUERY (2): + The backend metastore is BigQuery. + DATAPROC_METASTORE (3): + The backend metastore is Dataproc Metastore. + """ + METASTORE_TYPE_UNSPECIFIED = 0 + BIGQUERY = 2 + DATAPROC_METASTORE = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + metastore_type: MetastoreType = proto.Field( + proto.ENUM, + number=2, + enum=MetastoreType, + ) + + +class ListFederationsRequest(proto.Message): + r"""Request message for ListFederations. + + Attributes: + parent (str): + Required. The relative resource name of the location of + metastore federations to list, in the following form: + ``projects/{project_number}/locations/{location_id}``. + page_size (int): + Optional. The maximum number of federations + to return. The response may contain less than + the maximum number. If unspecified, no more than + 500 services are returned. The maximum value is + 1000; values above 1000 are changed to 1000. + page_token (str): + Optional. A page token, received from a + previous ListFederationServices call. Provide + this token to retrieve the subsequent page. + To retrieve the first page, supply an empty page + token. + When paginating, other parameters provided to + ListFederationServices must match the call that + provided the page token. + filter (str): + Optional. The filter to apply to list + results. + order_by (str): + Optional. Specify the ordering of results as described in + `Sorting + Order `__. + If not specified, the results will be sorted in the default + order. + """ + + 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 ListFederationsResponse(proto.Message): + r"""Response message for ListFederations + + Attributes: + federations (MutableSequence[google.cloud.metastore_v1beta.types.Federation]): + The services in the specified location. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + federations: MutableSequence['Federation'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Federation', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetFederationRequest(proto.Message): + r"""Request message for GetFederation. + + Attributes: + name (str): + Required. The relative resource name of the metastore + federation to retrieve, in the following form: + + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateFederationRequest(proto.Message): + r"""Request message for CreateFederation. + + Attributes: + parent (str): + Required. The relative resource name of the location in + which to create a federation service, in the following form: + + ``projects/{project_number}/locations/{location_id}``. + federation_id (str): + Required. The ID of the metastore federation, + which is used as the final component of the + metastore federation's name. + This value must be between 2 and 63 characters + long inclusive, begin with a letter, end with a + letter or number, and consist of alpha-numeric + ASCII characters or hyphens. + federation (google.cloud.metastore_v1beta.types.Federation): + Required. The Metastore Federation to create. The ``name`` + field is ignored. The ID of the created metastore federation + must be provided in the request's ``federation_id`` field. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + federation_id: str = proto.Field( + proto.STRING, + number=2, + ) + federation: 'Federation' = proto.Field( + proto.MESSAGE, + number=3, + message='Federation', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateFederationRequest(proto.Message): + r"""Request message for UpdateFederation. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask used to specify the fields to be + overwritten in the metastore federation resource by the + update. Fields specified in the ``update_mask`` are relative + to the resource (not to the full request). A field is + overwritten if it is in the mask. + federation (google.cloud.metastore_v1beta.types.Federation): + Required. The metastore federation to update. The server + only merges fields in the service if they are specified in + ``update_mask``. + + The metastore federation's ``name`` field is used to + identify the metastore service to be updated. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + federation: 'Federation' = proto.Field( + proto.MESSAGE, + number=2, + message='Federation', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteFederationRequest(proto.Message): + r"""Request message for DeleteFederation. + + Attributes: + name (str): + Required. The relative resource name of the metastore + federation to delete, in the following form: + + ``projects/{project_number}/locations/{location_id}/federations/{federation_id}``. + request_id (str): + Optional. A request ID. Specify a unique request ID to allow + the server to ignore the request if it has completed. The + server will ignore subsequent requests that provide a + duplicate request ID for at least 60 minutes after the first + request. + + For example, if an initial request times out, followed by + another request with the same request ID, the server ignores + the second request to prevent the creation of duplicate + commitments. + + The request ID must be a valid + `UUID `__ + A zero UUID (00000000-0000-0000-0000-000000000000) is not + supported. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/mypy.ini b/owl-bot-staging/v1beta/mypy.ini new file mode 100644 index 0000000..574c5ae --- /dev/null +++ b/owl-bot-staging/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1beta/noxfile.py b/owl-bot-staging/v1beta/noxfile.py new file mode 100644 index 0000000..c86b39f --- /dev/null +++ b/owl-bot-staging/v1beta/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "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/metastore_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-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/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_alter_metadata_resource_location_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_alter_metadata_resource_location_async.py new file mode 100644 index 0000000..cb49665 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_alter_metadata_resource_location_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AlterMetadataResourceLocation +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_AlterMetadataResourceLocation_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 metastore_v1beta + + +async def sample_alter_metadata_resource_location(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.AlterMetadataResourceLocationRequest( + service="service_value", + resource_name="resource_name_value", + location_uri="location_uri_value", + ) + + # Make the request + operation = client.alter_metadata_resource_location(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_AlterMetadataResourceLocation_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_alter_metadata_resource_location_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_alter_metadata_resource_location_sync.py new file mode 100644 index 0000000..b18add9 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_alter_metadata_resource_location_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AlterMetadataResourceLocation +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_AlterMetadataResourceLocation_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 metastore_v1beta + + +def sample_alter_metadata_resource_location(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.AlterMetadataResourceLocationRequest( + service="service_value", + resource_name="resource_name_value", + location_uri="location_uri_value", + ) + + # Make the request + operation = client.alter_metadata_resource_location(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_AlterMetadataResourceLocation_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_create_backup_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_create_backup_async.py new file mode 100644 index 0000000..3275001 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_create_backup_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateBackup +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_CreateBackup_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 metastore_v1beta + + +async def sample_create_backup(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + ) + + # Make the request + operation = client.create_backup(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_CreateBackup_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_create_backup_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_create_backup_sync.py new file mode 100644 index 0000000..c006d06 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_create_backup_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateBackup +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_CreateBackup_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 metastore_v1beta + + +def sample_create_backup(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + ) + + # Make the request + operation = client.create_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_CreateBackup_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_create_metadata_import_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_create_metadata_import_async.py new file mode 100644 index 0000000..db6db57 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_create_metadata_import_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMetadataImport +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_CreateMetadataImport_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 metastore_v1beta + + +async def sample_create_metadata_import(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.CreateMetadataImportRequest( + parent="parent_value", + metadata_import_id="metadata_import_id_value", + ) + + # Make the request + operation = client.create_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_CreateMetadataImport_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_create_metadata_import_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_create_metadata_import_sync.py new file mode 100644 index 0000000..5f6d5cc --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_create_metadata_import_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMetadataImport +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_CreateMetadataImport_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 metastore_v1beta + + +def sample_create_metadata_import(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.CreateMetadataImportRequest( + parent="parent_value", + metadata_import_id="metadata_import_id_value", + ) + + # Make the request + operation = client.create_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_CreateMetadataImport_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_create_service_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_create_service_async.py new file mode 100644 index 0000000..b241e92 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_create_service_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateService +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_CreateService_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 metastore_v1beta + + +async def sample_create_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.CreateServiceRequest( + parent="parent_value", + service_id="service_id_value", + ) + + # Make the request + operation = client.create_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_CreateService_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_create_service_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_create_service_sync.py new file mode 100644 index 0000000..40c3802 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_create_service_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateService +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_CreateService_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 metastore_v1beta + + +def sample_create_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.CreateServiceRequest( + parent="parent_value", + service_id="service_id_value", + ) + + # Make the request + operation = client.create_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_CreateService_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_delete_backup_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_delete_backup_async.py new file mode 100644 index 0000000..c8a7235 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_delete_backup_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteBackup +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_DeleteBackup_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 metastore_v1beta + + +async def sample_delete_backup(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_DeleteBackup_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_delete_backup_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_delete_backup_sync.py new file mode 100644 index 0000000..037ce3d --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_delete_backup_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteBackup +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_DeleteBackup_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 metastore_v1beta + + +def sample_delete_backup(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_DeleteBackup_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_delete_service_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_delete_service_async.py new file mode 100644 index 0000000..f71215a --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_delete_service_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteService +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_DeleteService_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 metastore_v1beta + + +async def sample_delete_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.DeleteServiceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_DeleteService_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_delete_service_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_delete_service_sync.py new file mode 100644 index 0000000..5581e47 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_delete_service_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteService +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_DeleteService_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 metastore_v1beta + + +def sample_delete_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.DeleteServiceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_DeleteService_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_export_metadata_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_export_metadata_async.py new file mode 100644 index 0000000..87373a6 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_export_metadata_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExportMetadata +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_ExportMetadata_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 metastore_v1beta + + +async def sample_export_metadata(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.ExportMetadataRequest( + destination_gcs_folder="destination_gcs_folder_value", + service="service_value", + ) + + # Make the request + operation = client.export_metadata(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_ExportMetadata_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_export_metadata_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_export_metadata_sync.py new file mode 100644 index 0000000..838022d --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_export_metadata_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExportMetadata +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_ExportMetadata_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 metastore_v1beta + + +def sample_export_metadata(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.ExportMetadataRequest( + destination_gcs_folder="destination_gcs_folder_value", + service="service_value", + ) + + # Make the request + operation = client.export_metadata(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_ExportMetadata_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_create_federation_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_create_federation_async.py new file mode 100644 index 0000000..a6b8058 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_create_federation_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateFederation +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastoreFederation_CreateFederation_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 metastore_v1beta + + +async def sample_create_federation(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.CreateFederationRequest( + parent="parent_value", + federation_id="federation_id_value", + ) + + # Make the request + operation = client.create_federation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastoreFederation_CreateFederation_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_create_federation_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_create_federation_sync.py new file mode 100644 index 0000000..2ed2ace --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_create_federation_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateFederation +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastoreFederation_CreateFederation_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 metastore_v1beta + + +def sample_create_federation(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1beta.CreateFederationRequest( + parent="parent_value", + federation_id="federation_id_value", + ) + + # Make the request + operation = client.create_federation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastoreFederation_CreateFederation_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_delete_federation_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_delete_federation_async.py new file mode 100644 index 0000000..1190fc2 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_delete_federation_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteFederation +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastoreFederation_DeleteFederation_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 metastore_v1beta + + +async def sample_delete_federation(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.DeleteFederationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_federation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastoreFederation_DeleteFederation_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_delete_federation_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_delete_federation_sync.py new file mode 100644 index 0000000..8bd5c31 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_delete_federation_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteFederation +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastoreFederation_DeleteFederation_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 metastore_v1beta + + +def sample_delete_federation(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1beta.DeleteFederationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_federation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastoreFederation_DeleteFederation_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_get_federation_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_get_federation_async.py new file mode 100644 index 0000000..c08cb2b --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_get_federation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFederation +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastoreFederation_GetFederation_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 metastore_v1beta + + +async def sample_get_federation(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.GetFederationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_federation(request=request) + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastoreFederation_GetFederation_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_get_federation_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_get_federation_sync.py new file mode 100644 index 0000000..d08b0db --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_get_federation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFederation +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastoreFederation_GetFederation_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 metastore_v1beta + + +def sample_get_federation(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1beta.GetFederationRequest( + name="name_value", + ) + + # Make the request + response = client.get_federation(request=request) + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastoreFederation_GetFederation_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_list_federations_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_list_federations_async.py new file mode 100644 index 0000000..57dcf17 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_list_federations_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListFederations +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastoreFederation_ListFederations_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 metastore_v1beta + + +async def sample_list_federations(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.ListFederationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_federations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END metastore_v1beta_generated_DataprocMetastoreFederation_ListFederations_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_list_federations_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_list_federations_sync.py new file mode 100644 index 0000000..13224ec --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_list_federations_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListFederations +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastoreFederation_ListFederations_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 metastore_v1beta + + +def sample_list_federations(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1beta.ListFederationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_federations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END metastore_v1beta_generated_DataprocMetastoreFederation_ListFederations_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_update_federation_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_update_federation_async.py new file mode 100644 index 0000000..1037451 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_update_federation_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateFederation +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastoreFederation_UpdateFederation_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 metastore_v1beta + + +async def sample_update_federation(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.UpdateFederationRequest( + ) + + # Make the request + operation = client.update_federation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastoreFederation_UpdateFederation_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_update_federation_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_update_federation_sync.py new file mode 100644 index 0000000..06d2b0d --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_federation_update_federation_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateFederation +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastoreFederation_UpdateFederation_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 metastore_v1beta + + +def sample_update_federation(): + # Create a client + client = metastore_v1beta.DataprocMetastoreFederationClient() + + # Initialize request argument(s) + request = metastore_v1beta.UpdateFederationRequest( + ) + + # Make the request + operation = client.update_federation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastoreFederation_UpdateFederation_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_get_backup_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_get_backup_async.py new file mode 100644 index 0000000..9c0b539 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_get_backup_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBackup +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_GetBackup_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 metastore_v1beta + + +async def sample_get_backup(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup(request=request) + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_GetBackup_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_get_backup_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_get_backup_sync.py new file mode 100644 index 0000000..ffae57e --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_get_backup_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBackup +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_GetBackup_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 metastore_v1beta + + +def sample_get_backup(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup(request=request) + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_GetBackup_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_get_metadata_import_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_get_metadata_import_async.py new file mode 100644 index 0000000..d822f53 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_get_metadata_import_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMetadataImport +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_GetMetadataImport_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 metastore_v1beta + + +async def sample_get_metadata_import(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.GetMetadataImportRequest( + name="name_value", + ) + + # Make the request + response = await client.get_metadata_import(request=request) + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_GetMetadataImport_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_get_metadata_import_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_get_metadata_import_sync.py new file mode 100644 index 0000000..76475ad --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_get_metadata_import_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMetadataImport +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_GetMetadataImport_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 metastore_v1beta + + +def sample_get_metadata_import(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.GetMetadataImportRequest( + name="name_value", + ) + + # Make the request + response = client.get_metadata_import(request=request) + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_GetMetadataImport_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_get_service_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_get_service_async.py new file mode 100644 index 0000000..450a8d6 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_get_service_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetService +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_GetService_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 metastore_v1beta + + +async def sample_get_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.GetServiceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_service(request=request) + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_GetService_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_get_service_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_get_service_sync.py new file mode 100644 index 0000000..83fcfeb --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_get_service_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetService +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_GetService_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 metastore_v1beta + + +def sample_get_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.GetServiceRequest( + name="name_value", + ) + + # Make the request + response = client.get_service(request=request) + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_GetService_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_list_backups_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_list_backups_async.py new file mode 100644 index 0000000..cae9194 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_list_backups_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBackups +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_ListBackups_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 metastore_v1beta + + +async def sample_list_backups(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_ListBackups_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_list_backups_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_list_backups_sync.py new file mode 100644 index 0000000..600f1e8 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_list_backups_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBackups +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_ListBackups_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 metastore_v1beta + + +def sample_list_backups(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_ListBackups_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_list_metadata_imports_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_list_metadata_imports_async.py new file mode 100644 index 0000000..afb8447 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_list_metadata_imports_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMetadataImports +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_ListMetadataImports_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 metastore_v1beta + + +async def sample_list_metadata_imports(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.ListMetadataImportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_metadata_imports(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_ListMetadataImports_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_list_metadata_imports_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_list_metadata_imports_sync.py new file mode 100644 index 0000000..cc7abf6 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_list_metadata_imports_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMetadataImports +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_ListMetadataImports_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 metastore_v1beta + + +def sample_list_metadata_imports(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.ListMetadataImportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_metadata_imports(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_ListMetadataImports_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_list_services_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_list_services_async.py new file mode 100644 index 0000000..df2bafd --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_list_services_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServices +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_ListServices_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 metastore_v1beta + + +async def sample_list_services(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.ListServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_ListServices_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_list_services_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_list_services_sync.py new file mode 100644 index 0000000..5aaf7e8 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_list_services_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServices +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_ListServices_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 metastore_v1beta + + +def sample_list_services(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.ListServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_ListServices_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_move_table_to_database_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_move_table_to_database_async.py new file mode 100644 index 0000000..a6927c9 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_move_table_to_database_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MoveTableToDatabase +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_MoveTableToDatabase_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 metastore_v1beta + + +async def sample_move_table_to_database(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.MoveTableToDatabaseRequest( + service="service_value", + table_name="table_name_value", + db_name="db_name_value", + destination_db_name="destination_db_name_value", + ) + + # Make the request + operation = client.move_table_to_database(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_MoveTableToDatabase_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_move_table_to_database_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_move_table_to_database_sync.py new file mode 100644 index 0000000..ac55fd9 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_move_table_to_database_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MoveTableToDatabase +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_MoveTableToDatabase_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 metastore_v1beta + + +def sample_move_table_to_database(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.MoveTableToDatabaseRequest( + service="service_value", + table_name="table_name_value", + db_name="db_name_value", + destination_db_name="destination_db_name_value", + ) + + # Make the request + operation = client.move_table_to_database(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_MoveTableToDatabase_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_query_metadata_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_query_metadata_async.py new file mode 100644 index 0000000..5dbe9fc --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_query_metadata_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for QueryMetadata +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_QueryMetadata_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 metastore_v1beta + + +async def sample_query_metadata(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.QueryMetadataRequest( + service="service_value", + query="query_value", + ) + + # Make the request + operation = client.query_metadata(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_QueryMetadata_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_query_metadata_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_query_metadata_sync.py new file mode 100644 index 0000000..8d9987d --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_query_metadata_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for QueryMetadata +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_QueryMetadata_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 metastore_v1beta + + +def sample_query_metadata(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.QueryMetadataRequest( + service="service_value", + query="query_value", + ) + + # Make the request + operation = client.query_metadata(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_QueryMetadata_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_remove_iam_policy_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_remove_iam_policy_async.py new file mode 100644 index 0000000..52005cb --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_remove_iam_policy_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveIamPolicy +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_RemoveIamPolicy_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 metastore_v1beta + + +async def sample_remove_iam_policy(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.RemoveIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.remove_iam_policy(request=request) + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_RemoveIamPolicy_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_remove_iam_policy_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_remove_iam_policy_sync.py new file mode 100644 index 0000000..4b57b6f --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_remove_iam_policy_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveIamPolicy +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_RemoveIamPolicy_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 metastore_v1beta + + +def sample_remove_iam_policy(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.RemoveIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.remove_iam_policy(request=request) + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_RemoveIamPolicy_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_restore_service_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_restore_service_async.py new file mode 100644 index 0000000..94420c1 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_restore_service_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreService +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_RestoreService_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 metastore_v1beta + + +async def sample_restore_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.RestoreServiceRequest( + service="service_value", + backup="backup_value", + ) + + # Make the request + operation = client.restore_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_RestoreService_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_restore_service_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_restore_service_sync.py new file mode 100644 index 0000000..0965b75 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_restore_service_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreService +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_RestoreService_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 metastore_v1beta + + +def sample_restore_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.RestoreServiceRequest( + service="service_value", + backup="backup_value", + ) + + # Make the request + operation = client.restore_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_RestoreService_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_update_metadata_import_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_update_metadata_import_async.py new file mode 100644 index 0000000..003b7cf --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_update_metadata_import_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMetadataImport +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_UpdateMetadataImport_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 metastore_v1beta + + +async def sample_update_metadata_import(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.UpdateMetadataImportRequest( + ) + + # Make the request + operation = client.update_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_UpdateMetadataImport_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_update_metadata_import_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_update_metadata_import_sync.py new file mode 100644 index 0000000..d546a2f --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_update_metadata_import_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMetadataImport +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_UpdateMetadataImport_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 metastore_v1beta + + +def sample_update_metadata_import(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.UpdateMetadataImportRequest( + ) + + # Make the request + operation = client.update_metadata_import(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_UpdateMetadataImport_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_update_service_async.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_update_service_async.py new file mode 100644 index 0000000..98ecc0e --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_update_service_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateService +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_UpdateService_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 metastore_v1beta + + +async def sample_update_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreAsyncClient() + + # Initialize request argument(s) + request = metastore_v1beta.UpdateServiceRequest( + ) + + # Make the request + operation = client.update_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_UpdateService_async] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_update_service_sync.py b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_update_service_sync.py new file mode 100644 index 0000000..e8dbf76 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/metastore_v1beta_generated_dataproc_metastore_update_service_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateService +# 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-dataproc-metastore + + +# [START metastore_v1beta_generated_DataprocMetastore_UpdateService_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 metastore_v1beta + + +def sample_update_service(): + # Create a client + client = metastore_v1beta.DataprocMetastoreClient() + + # Initialize request argument(s) + request = metastore_v1beta.UpdateServiceRequest( + ) + + # Make the request + operation = client.update_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END metastore_v1beta_generated_DataprocMetastore_UpdateService_sync] diff --git a/owl-bot-staging/v1beta/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1beta.json b/owl-bot-staging/v1beta/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1beta.json new file mode 100644 index 0000000..4a03aa2 --- /dev/null +++ b/owl-bot-staging/v1beta/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1beta.json @@ -0,0 +1,3935 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.metastore.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-cloud-dataproc-metastore", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationAsyncClient", + "shortName": "DataprocMetastoreFederationAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationAsyncClient.create_federation", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation.CreateFederation", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "CreateFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.CreateFederationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "federation", + "type": "google.cloud.metastore_v1beta.types.Federation" + }, + { + "name": "federation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_federation" + }, + "description": "Sample for CreateFederation", + "file": "metastore_v1beta_generated_dataproc_metastore_federation_create_federation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastoreFederation_CreateFederation_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_federation_create_federation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationClient", + "shortName": "DataprocMetastoreFederationClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationClient.create_federation", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation.CreateFederation", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "CreateFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.CreateFederationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "federation", + "type": "google.cloud.metastore_v1beta.types.Federation" + }, + { + "name": "federation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_federation" + }, + "description": "Sample for CreateFederation", + "file": "metastore_v1beta_generated_dataproc_metastore_federation_create_federation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastoreFederation_CreateFederation_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_federation_create_federation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationAsyncClient", + "shortName": "DataprocMetastoreFederationAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationAsyncClient.delete_federation", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation.DeleteFederation", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "DeleteFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.DeleteFederationRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "delete_federation" + }, + "description": "Sample for DeleteFederation", + "file": "metastore_v1beta_generated_dataproc_metastore_federation_delete_federation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastoreFederation_DeleteFederation_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_federation_delete_federation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationClient", + "shortName": "DataprocMetastoreFederationClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationClient.delete_federation", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation.DeleteFederation", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "DeleteFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.DeleteFederationRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "delete_federation" + }, + "description": "Sample for DeleteFederation", + "file": "metastore_v1beta_generated_dataproc_metastore_federation_delete_federation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastoreFederation_DeleteFederation_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_federation_delete_federation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationAsyncClient", + "shortName": "DataprocMetastoreFederationAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationAsyncClient.get_federation", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation.GetFederation", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "GetFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.GetFederationRequest" + }, + { + "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.metastore_v1beta.types.Federation", + "shortName": "get_federation" + }, + "description": "Sample for GetFederation", + "file": "metastore_v1beta_generated_dataproc_metastore_federation_get_federation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastoreFederation_GetFederation_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": "metastore_v1beta_generated_dataproc_metastore_federation_get_federation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationClient", + "shortName": "DataprocMetastoreFederationClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationClient.get_federation", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation.GetFederation", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "GetFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.GetFederationRequest" + }, + { + "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.metastore_v1beta.types.Federation", + "shortName": "get_federation" + }, + "description": "Sample for GetFederation", + "file": "metastore_v1beta_generated_dataproc_metastore_federation_get_federation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastoreFederation_GetFederation_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": "metastore_v1beta_generated_dataproc_metastore_federation_get_federation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationAsyncClient", + "shortName": "DataprocMetastoreFederationAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationAsyncClient.list_federations", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation.ListFederations", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "ListFederations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.ListFederationsRequest" + }, + { + "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.metastore_v1beta.services.dataproc_metastore_federation.pagers.ListFederationsAsyncPager", + "shortName": "list_federations" + }, + "description": "Sample for ListFederations", + "file": "metastore_v1beta_generated_dataproc_metastore_federation_list_federations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastoreFederation_ListFederations_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": "metastore_v1beta_generated_dataproc_metastore_federation_list_federations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationClient", + "shortName": "DataprocMetastoreFederationClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationClient.list_federations", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation.ListFederations", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "ListFederations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.ListFederationsRequest" + }, + { + "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.metastore_v1beta.services.dataproc_metastore_federation.pagers.ListFederationsPager", + "shortName": "list_federations" + }, + "description": "Sample for ListFederations", + "file": "metastore_v1beta_generated_dataproc_metastore_federation_list_federations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastoreFederation_ListFederations_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": "metastore_v1beta_generated_dataproc_metastore_federation_list_federations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationAsyncClient", + "shortName": "DataprocMetastoreFederationAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationAsyncClient.update_federation", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation.UpdateFederation", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "UpdateFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.UpdateFederationRequest" + }, + { + "name": "federation", + "type": "google.cloud.metastore_v1beta.types.Federation" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "update_federation" + }, + "description": "Sample for UpdateFederation", + "file": "metastore_v1beta_generated_dataproc_metastore_federation_update_federation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastoreFederation_UpdateFederation_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_federation_update_federation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationClient", + "shortName": "DataprocMetastoreFederationClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreFederationClient.update_federation", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation.UpdateFederation", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastoreFederation", + "shortName": "DataprocMetastoreFederation" + }, + "shortName": "UpdateFederation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.UpdateFederationRequest" + }, + { + "name": "federation", + "type": "google.cloud.metastore_v1beta.types.Federation" + }, + { + "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.api_core.operation.Operation", + "shortName": "update_federation" + }, + "description": "Sample for UpdateFederation", + "file": "metastore_v1beta_generated_dataproc_metastore_federation_update_federation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastoreFederation_UpdateFederation_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_federation_update_federation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.alter_metadata_resource_location", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.AlterMetadataResourceLocation", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "AlterMetadataResourceLocation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.AlterMetadataResourceLocationRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "alter_metadata_resource_location" + }, + "description": "Sample for AlterMetadataResourceLocation", + "file": "metastore_v1beta_generated_dataproc_metastore_alter_metadata_resource_location_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_AlterMetadataResourceLocation_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_alter_metadata_resource_location_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.alter_metadata_resource_location", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.AlterMetadataResourceLocation", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "AlterMetadataResourceLocation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.AlterMetadataResourceLocationRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "alter_metadata_resource_location" + }, + "description": "Sample for AlterMetadataResourceLocation", + "file": "metastore_v1beta_generated_dataproc_metastore_alter_metadata_resource_location_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_AlterMetadataResourceLocation_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_alter_metadata_resource_location_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.create_backup", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.CreateBackup", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "CreateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.CreateBackupRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup", + "type": "google.cloud.metastore_v1beta.types.Backup" + }, + { + "name": "backup_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_backup" + }, + "description": "Sample for CreateBackup", + "file": "metastore_v1beta_generated_dataproc_metastore_create_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_CreateBackup_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_create_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.create_backup", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.CreateBackup", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "CreateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.CreateBackupRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup", + "type": "google.cloud.metastore_v1beta.types.Backup" + }, + { + "name": "backup_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_backup" + }, + "description": "Sample for CreateBackup", + "file": "metastore_v1beta_generated_dataproc_metastore_create_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_CreateBackup_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_create_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.create_metadata_import", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.CreateMetadataImport", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "CreateMetadataImport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.CreateMetadataImportRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "metadata_import", + "type": "google.cloud.metastore_v1beta.types.MetadataImport" + }, + { + "name": "metadata_import_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_metadata_import" + }, + "description": "Sample for CreateMetadataImport", + "file": "metastore_v1beta_generated_dataproc_metastore_create_metadata_import_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_CreateMetadataImport_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_create_metadata_import_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.create_metadata_import", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.CreateMetadataImport", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "CreateMetadataImport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.CreateMetadataImportRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "metadata_import", + "type": "google.cloud.metastore_v1beta.types.MetadataImport" + }, + { + "name": "metadata_import_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_metadata_import" + }, + "description": "Sample for CreateMetadataImport", + "file": "metastore_v1beta_generated_dataproc_metastore_create_metadata_import_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_CreateMetadataImport_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_create_metadata_import_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.create_service", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.CreateService", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "CreateService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.CreateServiceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "service", + "type": "google.cloud.metastore_v1beta.types.Service" + }, + { + "name": "service_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_service" + }, + "description": "Sample for CreateService", + "file": "metastore_v1beta_generated_dataproc_metastore_create_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_CreateService_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_create_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.create_service", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.CreateService", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "CreateService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.CreateServiceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "service", + "type": "google.cloud.metastore_v1beta.types.Service" + }, + { + "name": "service_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_service" + }, + "description": "Sample for CreateService", + "file": "metastore_v1beta_generated_dataproc_metastore_create_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_CreateService_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_create_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.delete_backup", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.DeleteBackup", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.DeleteBackupRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "delete_backup" + }, + "description": "Sample for DeleteBackup", + "file": "metastore_v1beta_generated_dataproc_metastore_delete_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_DeleteBackup_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_delete_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.delete_backup", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.DeleteBackup", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.DeleteBackupRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "delete_backup" + }, + "description": "Sample for DeleteBackup", + "file": "metastore_v1beta_generated_dataproc_metastore_delete_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_DeleteBackup_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_delete_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.delete_service", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.DeleteService", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "DeleteService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.DeleteServiceRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "delete_service" + }, + "description": "Sample for DeleteService", + "file": "metastore_v1beta_generated_dataproc_metastore_delete_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_DeleteService_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_delete_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.delete_service", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.DeleteService", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "DeleteService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.DeleteServiceRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "delete_service" + }, + "description": "Sample for DeleteService", + "file": "metastore_v1beta_generated_dataproc_metastore_delete_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_DeleteService_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_delete_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.export_metadata", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.ExportMetadata", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ExportMetadata" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.ExportMetadataRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "export_metadata" + }, + "description": "Sample for ExportMetadata", + "file": "metastore_v1beta_generated_dataproc_metastore_export_metadata_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_ExportMetadata_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_export_metadata_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.export_metadata", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.ExportMetadata", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ExportMetadata" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.ExportMetadataRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "export_metadata" + }, + "description": "Sample for ExportMetadata", + "file": "metastore_v1beta_generated_dataproc_metastore_export_metadata_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_ExportMetadata_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_export_metadata_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.get_backup", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.GetBackup", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.GetBackupRequest" + }, + { + "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.metastore_v1beta.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "metastore_v1beta_generated_dataproc_metastore_get_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_GetBackup_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": "metastore_v1beta_generated_dataproc_metastore_get_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.get_backup", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.GetBackup", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.GetBackupRequest" + }, + { + "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.metastore_v1beta.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "metastore_v1beta_generated_dataproc_metastore_get_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_GetBackup_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": "metastore_v1beta_generated_dataproc_metastore_get_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.get_metadata_import", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.GetMetadataImport", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "GetMetadataImport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.GetMetadataImportRequest" + }, + { + "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.metastore_v1beta.types.MetadataImport", + "shortName": "get_metadata_import" + }, + "description": "Sample for GetMetadataImport", + "file": "metastore_v1beta_generated_dataproc_metastore_get_metadata_import_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_GetMetadataImport_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": "metastore_v1beta_generated_dataproc_metastore_get_metadata_import_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.get_metadata_import", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.GetMetadataImport", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "GetMetadataImport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.GetMetadataImportRequest" + }, + { + "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.metastore_v1beta.types.MetadataImport", + "shortName": "get_metadata_import" + }, + "description": "Sample for GetMetadataImport", + "file": "metastore_v1beta_generated_dataproc_metastore_get_metadata_import_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_GetMetadataImport_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": "metastore_v1beta_generated_dataproc_metastore_get_metadata_import_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.get_service", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.GetService", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "GetService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.GetServiceRequest" + }, + { + "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.metastore_v1beta.types.Service", + "shortName": "get_service" + }, + "description": "Sample for GetService", + "file": "metastore_v1beta_generated_dataproc_metastore_get_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_GetService_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": "metastore_v1beta_generated_dataproc_metastore_get_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.get_service", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.GetService", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "GetService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.GetServiceRequest" + }, + { + "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.metastore_v1beta.types.Service", + "shortName": "get_service" + }, + "description": "Sample for GetService", + "file": "metastore_v1beta_generated_dataproc_metastore_get_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_GetService_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": "metastore_v1beta_generated_dataproc_metastore_get_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.list_backups", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.ListBackups", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ListBackups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.ListBackupsRequest" + }, + { + "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.metastore_v1beta.services.dataproc_metastore.pagers.ListBackupsAsyncPager", + "shortName": "list_backups" + }, + "description": "Sample for ListBackups", + "file": "metastore_v1beta_generated_dataproc_metastore_list_backups_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_ListBackups_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": "metastore_v1beta_generated_dataproc_metastore_list_backups_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.list_backups", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.ListBackups", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ListBackups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.ListBackupsRequest" + }, + { + "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.metastore_v1beta.services.dataproc_metastore.pagers.ListBackupsPager", + "shortName": "list_backups" + }, + "description": "Sample for ListBackups", + "file": "metastore_v1beta_generated_dataproc_metastore_list_backups_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_ListBackups_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": "metastore_v1beta_generated_dataproc_metastore_list_backups_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.list_metadata_imports", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.ListMetadataImports", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ListMetadataImports" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.ListMetadataImportsRequest" + }, + { + "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.metastore_v1beta.services.dataproc_metastore.pagers.ListMetadataImportsAsyncPager", + "shortName": "list_metadata_imports" + }, + "description": "Sample for ListMetadataImports", + "file": "metastore_v1beta_generated_dataproc_metastore_list_metadata_imports_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_ListMetadataImports_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": "metastore_v1beta_generated_dataproc_metastore_list_metadata_imports_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.list_metadata_imports", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.ListMetadataImports", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ListMetadataImports" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.ListMetadataImportsRequest" + }, + { + "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.metastore_v1beta.services.dataproc_metastore.pagers.ListMetadataImportsPager", + "shortName": "list_metadata_imports" + }, + "description": "Sample for ListMetadataImports", + "file": "metastore_v1beta_generated_dataproc_metastore_list_metadata_imports_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_ListMetadataImports_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": "metastore_v1beta_generated_dataproc_metastore_list_metadata_imports_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.list_services", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.ListServices", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ListServices" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.ListServicesRequest" + }, + { + "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.metastore_v1beta.services.dataproc_metastore.pagers.ListServicesAsyncPager", + "shortName": "list_services" + }, + "description": "Sample for ListServices", + "file": "metastore_v1beta_generated_dataproc_metastore_list_services_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_ListServices_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": "metastore_v1beta_generated_dataproc_metastore_list_services_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.list_services", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.ListServices", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "ListServices" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.ListServicesRequest" + }, + { + "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.metastore_v1beta.services.dataproc_metastore.pagers.ListServicesPager", + "shortName": "list_services" + }, + "description": "Sample for ListServices", + "file": "metastore_v1beta_generated_dataproc_metastore_list_services_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_ListServices_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": "metastore_v1beta_generated_dataproc_metastore_list_services_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.move_table_to_database", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.MoveTableToDatabase", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "MoveTableToDatabase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.MoveTableToDatabaseRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "move_table_to_database" + }, + "description": "Sample for MoveTableToDatabase", + "file": "metastore_v1beta_generated_dataproc_metastore_move_table_to_database_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_MoveTableToDatabase_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_move_table_to_database_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.move_table_to_database", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.MoveTableToDatabase", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "MoveTableToDatabase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.MoveTableToDatabaseRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "move_table_to_database" + }, + "description": "Sample for MoveTableToDatabase", + "file": "metastore_v1beta_generated_dataproc_metastore_move_table_to_database_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_MoveTableToDatabase_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_move_table_to_database_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.query_metadata", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.QueryMetadata", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "QueryMetadata" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.QueryMetadataRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "query_metadata" + }, + "description": "Sample for QueryMetadata", + "file": "metastore_v1beta_generated_dataproc_metastore_query_metadata_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_QueryMetadata_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_query_metadata_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.query_metadata", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.QueryMetadata", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "QueryMetadata" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.QueryMetadataRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "query_metadata" + }, + "description": "Sample for QueryMetadata", + "file": "metastore_v1beta_generated_dataproc_metastore_query_metadata_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_QueryMetadata_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_query_metadata_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.remove_iam_policy", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.RemoveIamPolicy", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "RemoveIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.RemoveIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.metastore_v1beta.types.RemoveIamPolicyResponse", + "shortName": "remove_iam_policy" + }, + "description": "Sample for RemoveIamPolicy", + "file": "metastore_v1beta_generated_dataproc_metastore_remove_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_RemoveIamPolicy_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": "metastore_v1beta_generated_dataproc_metastore_remove_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.remove_iam_policy", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.RemoveIamPolicy", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "RemoveIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.RemoveIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.metastore_v1beta.types.RemoveIamPolicyResponse", + "shortName": "remove_iam_policy" + }, + "description": "Sample for RemoveIamPolicy", + "file": "metastore_v1beta_generated_dataproc_metastore_remove_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_RemoveIamPolicy_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": "metastore_v1beta_generated_dataproc_metastore_remove_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.restore_service", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.RestoreService", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "RestoreService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.RestoreServiceRequest" + }, + { + "name": "service", + "type": "str" + }, + { + "name": "backup", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "restore_service" + }, + "description": "Sample for RestoreService", + "file": "metastore_v1beta_generated_dataproc_metastore_restore_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_RestoreService_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_restore_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.restore_service", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.RestoreService", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "RestoreService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.RestoreServiceRequest" + }, + { + "name": "service", + "type": "str" + }, + { + "name": "backup", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "restore_service" + }, + "description": "Sample for RestoreService", + "file": "metastore_v1beta_generated_dataproc_metastore_restore_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_RestoreService_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_restore_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.update_metadata_import", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.UpdateMetadataImport", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "UpdateMetadataImport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.UpdateMetadataImportRequest" + }, + { + "name": "metadata_import", + "type": "google.cloud.metastore_v1beta.types.MetadataImport" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "update_metadata_import" + }, + "description": "Sample for UpdateMetadataImport", + "file": "metastore_v1beta_generated_dataproc_metastore_update_metadata_import_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_UpdateMetadataImport_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_update_metadata_import_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.update_metadata_import", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.UpdateMetadataImport", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "UpdateMetadataImport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.UpdateMetadataImportRequest" + }, + { + "name": "metadata_import", + "type": "google.cloud.metastore_v1beta.types.MetadataImport" + }, + { + "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.api_core.operation.Operation", + "shortName": "update_metadata_import" + }, + "description": "Sample for UpdateMetadataImport", + "file": "metastore_v1beta_generated_dataproc_metastore_update_metadata_import_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_UpdateMetadataImport_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_update_metadata_import_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient", + "shortName": "DataprocMetastoreAsyncClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreAsyncClient.update_service", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.UpdateService", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "UpdateService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.UpdateServiceRequest" + }, + { + "name": "service", + "type": "google.cloud.metastore_v1beta.types.Service" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "update_service" + }, + "description": "Sample for UpdateService", + "file": "metastore_v1beta_generated_dataproc_metastore_update_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_UpdateService_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_update_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient", + "shortName": "DataprocMetastoreClient" + }, + "fullName": "google.cloud.metastore_v1beta.DataprocMetastoreClient.update_service", + "method": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore.UpdateService", + "service": { + "fullName": "google.cloud.metastore.v1beta.DataprocMetastore", + "shortName": "DataprocMetastore" + }, + "shortName": "UpdateService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.metastore_v1beta.types.UpdateServiceRequest" + }, + { + "name": "service", + "type": "google.cloud.metastore_v1beta.types.Service" + }, + { + "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.api_core.operation.Operation", + "shortName": "update_service" + }, + "description": "Sample for UpdateService", + "file": "metastore_v1beta_generated_dataproc_metastore_update_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "metastore_v1beta_generated_DataprocMetastore_UpdateService_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "metastore_v1beta_generated_dataproc_metastore_update_service_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1beta/scripts/fixup_metastore_v1beta_keywords.py b/owl-bot-staging/v1beta/scripts/fixup_metastore_v1beta_keywords.py new file mode 100644 index 0000000..418ffb6 --- /dev/null +++ b/owl-bot-staging/v1beta/scripts/fixup_metastore_v1beta_keywords.py @@ -0,0 +1,199 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class metastoreCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'alter_metadata_resource_location': ('service', 'resource_name', 'location_uri', ), + 'create_backup': ('parent', 'backup_id', 'backup', 'request_id', ), + 'create_federation': ('parent', 'federation_id', 'federation', 'request_id', ), + 'create_metadata_import': ('parent', 'metadata_import_id', 'metadata_import', 'request_id', ), + 'create_service': ('parent', 'service_id', 'service', 'request_id', ), + 'delete_backup': ('name', 'request_id', ), + 'delete_federation': ('name', 'request_id', ), + 'delete_service': ('name', 'request_id', ), + 'export_metadata': ('service', 'destination_gcs_folder', 'request_id', 'database_dump_type', ), + 'get_backup': ('name', ), + 'get_federation': ('name', ), + 'get_metadata_import': ('name', ), + 'get_service': ('name', ), + 'list_backups': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_federations': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_metadata_imports': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_services': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'move_table_to_database': ('service', 'table_name', 'db_name', 'destination_db_name', ), + 'query_metadata': ('service', 'query', ), + 'remove_iam_policy': ('resource', 'asynchronous', ), + 'restore_service': ('service', 'backup', 'restore_type', 'request_id', ), + 'update_federation': ('update_mask', 'federation', 'request_id', ), + 'update_metadata_import': ('update_mask', 'metadata_import', 'request_id', ), + 'update_service': ('update_mask', 'service', '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=metastoreCallTransformer(), +): + """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 metastore client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1beta/setup.py b/owl-bot-staging/v1beta/setup.py new file mode 100644 index 0000000..3b0acfa --- /dev/null +++ b/owl-bot-staging/v1beta/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-dataproc-metastore' + + +description = "Google Cloud Dataproc Metastore API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/metastore/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", + "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", +] +url = "https://github.com/googleapis/python-dataproc-metastore" + +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/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/v1beta/testing/constraints-3.10.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1beta/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/v1beta/testing/constraints-3.11.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1beta/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/v1beta/testing/constraints-3.12.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1beta/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/v1beta/testing/constraints-3.7.txt new file mode 100644 index 0000000..2beecf9 --- /dev/null +++ b/owl-bot-staging/v1beta/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 +grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/v1beta/testing/constraints-3.8.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1beta/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/v1beta/testing/constraints-3.9.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1beta/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1beta/tests/__init__.py b/owl-bot-staging/v1beta/tests/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta/tests/unit/__init__.py b/owl-bot-staging/v1beta/tests/unit/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta/tests/unit/gapic/metastore_v1beta/__init__.py b/owl-bot-staging/v1beta/tests/unit/gapic/metastore_v1beta/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1beta/tests/unit/gapic/metastore_v1beta/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta/tests/unit/gapic/metastore_v1beta/test_dataproc_metastore.py b/owl-bot-staging/v1beta/tests/unit/gapic/metastore_v1beta/test_dataproc_metastore.py new file mode 100644 index 0000000..8146f28 --- /dev/null +++ b/owl-bot-staging/v1beta/tests/unit/gapic/metastore_v1beta/test_dataproc_metastore.py @@ -0,0 +1,12069 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.metastore_v1beta.services.dataproc_metastore import DataprocMetastoreAsyncClient +from google.cloud.metastore_v1beta.services.dataproc_metastore import DataprocMetastoreClient +from google.cloud.metastore_v1beta.services.dataproc_metastore import pagers +from google.cloud.metastore_v1beta.services.dataproc_metastore import transports +from google.cloud.metastore_v1beta.types import metastore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import dayofweek_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 DataprocMetastoreClient._get_default_mtls_endpoint(None) is None + assert DataprocMetastoreClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DataprocMetastoreClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DataprocMetastoreClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DataprocMetastoreClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DataprocMetastoreClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DataprocMetastoreClient, "grpc"), + (DataprocMetastoreAsyncClient, "grpc_asyncio"), + (DataprocMetastoreClient, "rest"), +]) +def test_dataproc_metastore_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 == ( + 'metastore.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://metastore.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DataprocMetastoreGrpcTransport, "grpc"), + (transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DataprocMetastoreRestTransport, "rest"), +]) +def test_dataproc_metastore_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", [ + (DataprocMetastoreClient, "grpc"), + (DataprocMetastoreAsyncClient, "grpc_asyncio"), + (DataprocMetastoreClient, "rest"), +]) +def test_dataproc_metastore_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 == ( + 'metastore.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://metastore.googleapis.com' + ) + + +def test_dataproc_metastore_client_get_transport_class(): + transport = DataprocMetastoreClient.get_transport_class() + available_transports = [ + transports.DataprocMetastoreGrpcTransport, + transports.DataprocMetastoreRestTransport, + ] + assert transport in available_transports + + transport = DataprocMetastoreClient.get_transport_class("grpc") + assert transport == transports.DataprocMetastoreGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport, "grpc"), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio"), + (DataprocMetastoreClient, transports.DataprocMetastoreRestTransport, "rest"), +]) +@mock.patch.object(DataprocMetastoreClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreClient)) +@mock.patch.object(DataprocMetastoreAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreAsyncClient)) +def test_dataproc_metastore_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(DataprocMetastoreClient, '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(DataprocMetastoreClient, '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", [ + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport, "grpc", "true"), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport, "grpc", "false"), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (DataprocMetastoreClient, transports.DataprocMetastoreRestTransport, "rest", "true"), + (DataprocMetastoreClient, transports.DataprocMetastoreRestTransport, "rest", "false"), +]) +@mock.patch.object(DataprocMetastoreClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreClient)) +@mock.patch.object(DataprocMetastoreAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_dataproc_metastore_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", [ + DataprocMetastoreClient, DataprocMetastoreAsyncClient +]) +@mock.patch.object(DataprocMetastoreClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreClient)) +@mock.patch.object(DataprocMetastoreAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreAsyncClient)) +def test_dataproc_metastore_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", [ + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport, "grpc"), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio"), + (DataprocMetastoreClient, transports.DataprocMetastoreRestTransport, "rest"), +]) +def test_dataproc_metastore_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", [ + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport, "grpc", grpc_helpers), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (DataprocMetastoreClient, transports.DataprocMetastoreRestTransport, "rest", None), +]) +def test_dataproc_metastore_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_dataproc_metastore_client_client_options_from_dict(): + with mock.patch('google.cloud.metastore_v1beta.services.dataproc_metastore.transports.DataprocMetastoreGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DataprocMetastoreClient( + 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", [ + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport, "grpc", grpc_helpers), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_dataproc_metastore_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( + "metastore.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="metastore.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ListServicesRequest, + dict, +]) +def test_list_services(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListServicesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListServicesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_services_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_services), + '__call__') as call: + client.list_services() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListServicesRequest() + +@pytest.mark.asyncio +async def test_list_services_async(transport: str = 'grpc_asyncio', request_type=metastore.ListServicesRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListServicesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListServicesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_services_async_from_dict(): + await test_list_services_async(request_type=dict) + + +def test_list_services_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ListServicesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + call.return_value = metastore.ListServicesResponse() + client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_services_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ListServicesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListServicesResponse()) + await client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_services_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListServicesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_services( + 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_services_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_services( + metastore.ListServicesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_services_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListServicesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListServicesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_services( + 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_services_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_services( + metastore.ListServicesRequest(), + parent='parent_value', + ) + + +def test_list_services_pager(transport_name: str = "grpc"): + client = DataprocMetastoreClient( + 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_services), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + metastore.Service(), + ], + next_page_token='abc', + ), + metastore.ListServicesResponse( + services=[], + next_page_token='def', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + ], + next_page_token='ghi', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_services(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore.Service) + for i in results) +def test_list_services_pages(transport_name: str = "grpc"): + client = DataprocMetastoreClient( + 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_services), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + metastore.Service(), + ], + next_page_token='abc', + ), + metastore.ListServicesResponse( + services=[], + next_page_token='def', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + ], + next_page_token='ghi', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + ], + ), + RuntimeError, + ) + pages = list(client.list_services(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_services_async_pager(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + metastore.Service(), + ], + next_page_token='abc', + ), + metastore.ListServicesResponse( + services=[], + next_page_token='def', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + ], + next_page_token='ghi', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_services(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, metastore.Service) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_services_async_pages(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + metastore.Service(), + ], + next_page_token='abc', + ), + metastore.ListServicesResponse( + services=[], + next_page_token='def', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + ], + next_page_token='ghi', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_services(request={})).pages: # pragma: no branch + 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", [ + metastore.GetServiceRequest, + dict, +]) +def test_get_service(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.Service( + name='name_value', + network='network_value', + endpoint_uri='endpoint_uri_value', + port=453, + state=metastore.Service.State.CREATING, + state_message='state_message_value', + artifact_gcs_uri='artifact_gcs_uri_value', + tier=metastore.Service.Tier.DEVELOPER, + uid='uid_value', + release_channel=metastore.Service.ReleaseChannel.CANARY, + database_type=metastore.Service.DatabaseType.MYSQL, + hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value'), + ) + response = client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.Service) + assert response.name == 'name_value' + assert response.network == 'network_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.port == 453 + assert response.state == metastore.Service.State.CREATING + assert response.state_message == 'state_message_value' + assert response.artifact_gcs_uri == 'artifact_gcs_uri_value' + assert response.tier == metastore.Service.Tier.DEVELOPER + assert response.uid == 'uid_value' + assert response.release_channel == metastore.Service.ReleaseChannel.CANARY + assert response.database_type == metastore.Service.DatabaseType.MYSQL + + +def test_get_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_service), + '__call__') as call: + client.get_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetServiceRequest() + +@pytest.mark.asyncio +async def test_get_service_async(transport: str = 'grpc_asyncio', request_type=metastore.GetServiceRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.Service( + name='name_value', + network='network_value', + endpoint_uri='endpoint_uri_value', + port=453, + state=metastore.Service.State.CREATING, + state_message='state_message_value', + artifact_gcs_uri='artifact_gcs_uri_value', + tier=metastore.Service.Tier.DEVELOPER, + uid='uid_value', + release_channel=metastore.Service.ReleaseChannel.CANARY, + database_type=metastore.Service.DatabaseType.MYSQL, + )) + response = await client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.Service) + assert response.name == 'name_value' + assert response.network == 'network_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.port == 453 + assert response.state == metastore.Service.State.CREATING + assert response.state_message == 'state_message_value' + assert response.artifact_gcs_uri == 'artifact_gcs_uri_value' + assert response.tier == metastore.Service.Tier.DEVELOPER + assert response.uid == 'uid_value' + assert response.release_channel == metastore.Service.ReleaseChannel.CANARY + assert response.database_type == metastore.Service.DatabaseType.MYSQL + + +@pytest.mark.asyncio +async def test_get_service_async_from_dict(): + await test_get_service_async(request_type=dict) + + +def test_get_service_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.GetServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + call.return_value = metastore.Service() + client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_service_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.GetServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.Service()) + await client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_service_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.Service() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_service( + 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_service_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_service( + metastore.GetServiceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_service_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.Service() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.Service()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_service( + 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_service_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_service( + metastore.GetServiceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.CreateServiceRequest, + dict, +]) +def test_create_service(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_service), + '__call__') as call: + client.create_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateServiceRequest() + +@pytest.mark.asyncio +async def test_create_service_async(transport: str = 'grpc_asyncio', request_type=metastore.CreateServiceRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_service_async_from_dict(): + await test_create_service_async(request_type=dict) + + +def test_create_service_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.CreateServiceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_service_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.CreateServiceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_service_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_service( + parent='parent_value', + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + service_id='service_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].service + mock_val = metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')) + assert arg == mock_val + arg = args[0].service_id + mock_val = 'service_id_value' + assert arg == mock_val + + +def test_create_service_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_service( + metastore.CreateServiceRequest(), + parent='parent_value', + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + service_id='service_id_value', + ) + +@pytest.mark.asyncio +async def test_create_service_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_service( + parent='parent_value', + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + service_id='service_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].service + mock_val = metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')) + assert arg == mock_val + arg = args[0].service_id + mock_val = 'service_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_service_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_service( + metastore.CreateServiceRequest(), + parent='parent_value', + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + service_id='service_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.UpdateServiceRequest, + dict, +]) +def test_update_service(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.UpdateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_service), + '__call__') as call: + client.update_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.UpdateServiceRequest() + +@pytest.mark.asyncio +async def test_update_service_async(transport: str = 'grpc_asyncio', request_type=metastore.UpdateServiceRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.UpdateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_service_async_from_dict(): + await test_update_service_async(request_type=dict) + + +def test_update_service_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.UpdateServiceRequest() + + request.service.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_service_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.UpdateServiceRequest() + + request.service.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service.name=name_value', + ) in kw['metadata'] + + +def test_update_service_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_service( + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_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].service + mock_val = metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_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_service_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_service( + metastore.UpdateServiceRequest(), + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_service_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_service( + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_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].service + mock_val = metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_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_service_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_service( + metastore.UpdateServiceRequest(), + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.DeleteServiceRequest, + dict, +]) +def test_delete_service(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.DeleteServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_service), + '__call__') as call: + client.delete_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.DeleteServiceRequest() + +@pytest.mark.asyncio +async def test_delete_service_async(transport: str = 'grpc_asyncio', request_type=metastore.DeleteServiceRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.DeleteServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_service_async_from_dict(): + await test_delete_service_async(request_type=dict) + + +def test_delete_service_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.DeleteServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_service_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.DeleteServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_service_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_service( + 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_service_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_service( + metastore.DeleteServiceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_service_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_service( + 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_service_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_service( + metastore.DeleteServiceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ListMetadataImportsRequest, + dict, +]) +def test_list_metadata_imports(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata_imports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListMetadataImportsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_metadata_imports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListMetadataImportsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMetadataImportsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_metadata_imports_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_metadata_imports), + '__call__') as call: + client.list_metadata_imports() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListMetadataImportsRequest() + +@pytest.mark.asyncio +async def test_list_metadata_imports_async(transport: str = 'grpc_asyncio', request_type=metastore.ListMetadataImportsRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata_imports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListMetadataImportsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_metadata_imports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListMetadataImportsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMetadataImportsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_metadata_imports_async_from_dict(): + await test_list_metadata_imports_async(request_type=dict) + + +def test_list_metadata_imports_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ListMetadataImportsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_metadata_imports), + '__call__') as call: + call.return_value = metastore.ListMetadataImportsResponse() + client.list_metadata_imports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_metadata_imports_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ListMetadataImportsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_metadata_imports), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListMetadataImportsResponse()) + await client.list_metadata_imports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_metadata_imports_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_metadata_imports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListMetadataImportsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_metadata_imports( + 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_metadata_imports_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_metadata_imports( + metastore.ListMetadataImportsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_metadata_imports_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_metadata_imports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListMetadataImportsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListMetadataImportsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_metadata_imports( + 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_metadata_imports_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_metadata_imports( + metastore.ListMetadataImportsRequest(), + parent='parent_value', + ) + + +def test_list_metadata_imports_pager(transport_name: str = "grpc"): + client = DataprocMetastoreClient( + 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_metadata_imports), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + next_page_token='abc', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[], + next_page_token='def', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + ], + next_page_token='ghi', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_metadata_imports(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore.MetadataImport) + for i in results) +def test_list_metadata_imports_pages(transport_name: str = "grpc"): + client = DataprocMetastoreClient( + 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_metadata_imports), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + next_page_token='abc', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[], + next_page_token='def', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + ], + next_page_token='ghi', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + ), + RuntimeError, + ) + pages = list(client.list_metadata_imports(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_metadata_imports_async_pager(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_metadata_imports), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + next_page_token='abc', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[], + next_page_token='def', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + ], + next_page_token='ghi', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_metadata_imports(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, metastore.MetadataImport) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_metadata_imports_async_pages(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_metadata_imports), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + next_page_token='abc', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[], + next_page_token='def', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + ], + next_page_token='ghi', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_metadata_imports(request={})).pages: # pragma: no branch + 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", [ + metastore.GetMetadataImportRequest, + dict, +]) +def test_get_metadata_import(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.MetadataImport( + name='name_value', + description='description_value', + state=metastore.MetadataImport.State.RUNNING, + database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL), + ) + response = client.get_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetMetadataImportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.MetadataImport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == metastore.MetadataImport.State.RUNNING + + +def test_get_metadata_import_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + client.get_metadata_import() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetMetadataImportRequest() + +@pytest.mark.asyncio +async def test_get_metadata_import_async(transport: str = 'grpc_asyncio', request_type=metastore.GetMetadataImportRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.MetadataImport( + name='name_value', + description='description_value', + state=metastore.MetadataImport.State.RUNNING, + )) + response = await client.get_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetMetadataImportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.MetadataImport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == metastore.MetadataImport.State.RUNNING + + +@pytest.mark.asyncio +async def test_get_metadata_import_async_from_dict(): + await test_get_metadata_import_async(request_type=dict) + + +def test_get_metadata_import_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.GetMetadataImportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + call.return_value = metastore.MetadataImport() + client.get_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_metadata_import_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.GetMetadataImportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.MetadataImport()) + await client.get_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_metadata_import_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.MetadataImport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_metadata_import( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_metadata_import_flattened_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_metadata_import( + metastore.GetMetadataImportRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_metadata_import_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.MetadataImport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.MetadataImport()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_metadata_import( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_metadata_import_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_metadata_import( + metastore.GetMetadataImportRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.CreateMetadataImportRequest, + dict, +]) +def test_create_metadata_import(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateMetadataImportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_metadata_import_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_metadata_import), + '__call__') as call: + client.create_metadata_import() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateMetadataImportRequest() + +@pytest.mark.asyncio +async def test_create_metadata_import_async(transport: str = 'grpc_asyncio', request_type=metastore.CreateMetadataImportRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateMetadataImportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_metadata_import_async_from_dict(): + await test_create_metadata_import_async(request_type=dict) + + +def test_create_metadata_import_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.CreateMetadataImportRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_metadata_import), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_metadata_import_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.CreateMetadataImportRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_metadata_import), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_metadata_import_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_metadata_import( + parent='parent_value', + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + metadata_import_id='metadata_import_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].metadata_import + mock_val = metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)) + assert arg == mock_val + arg = args[0].metadata_import_id + mock_val = 'metadata_import_id_value' + assert arg == mock_val + + +def test_create_metadata_import_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_metadata_import( + metastore.CreateMetadataImportRequest(), + parent='parent_value', + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + metadata_import_id='metadata_import_id_value', + ) + +@pytest.mark.asyncio +async def test_create_metadata_import_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_metadata_import( + parent='parent_value', + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + metadata_import_id='metadata_import_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].metadata_import + mock_val = metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)) + assert arg == mock_val + arg = args[0].metadata_import_id + mock_val = 'metadata_import_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_metadata_import_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_metadata_import( + metastore.CreateMetadataImportRequest(), + parent='parent_value', + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + metadata_import_id='metadata_import_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.UpdateMetadataImportRequest, + dict, +]) +def test_update_metadata_import(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.UpdateMetadataImportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_metadata_import_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_metadata_import), + '__call__') as call: + client.update_metadata_import() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.UpdateMetadataImportRequest() + +@pytest.mark.asyncio +async def test_update_metadata_import_async(transport: str = 'grpc_asyncio', request_type=metastore.UpdateMetadataImportRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.UpdateMetadataImportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_metadata_import_async_from_dict(): + await test_update_metadata_import_async(request_type=dict) + + +def test_update_metadata_import_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.UpdateMetadataImportRequest() + + request.metadata_import.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_metadata_import), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'metadata_import.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_metadata_import_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.UpdateMetadataImportRequest() + + request.metadata_import.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_metadata_import), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_metadata_import(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'metadata_import.name=name_value', + ) in kw['metadata'] + + +def test_update_metadata_import_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_metadata_import( + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + 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].metadata_import + mock_val = metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)) + 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_metadata_import_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_metadata_import( + metastore.UpdateMetadataImportRequest(), + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_metadata_import_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_metadata_import), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_metadata_import( + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + 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].metadata_import + mock_val = metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)) + 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_metadata_import_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_metadata_import( + metastore.UpdateMetadataImportRequest(), + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ExportMetadataRequest, + dict, +]) +def test_export_metadata(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.export_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ExportMetadataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_metadata_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_metadata), + '__call__') as call: + client.export_metadata() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ExportMetadataRequest() + +@pytest.mark.asyncio +async def test_export_metadata_async(transport: str = 'grpc_asyncio', request_type=metastore.ExportMetadataRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.export_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ExportMetadataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_export_metadata_async_from_dict(): + await test_export_metadata_async(request_type=dict) + + +def test_export_metadata_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ExportMetadataRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_metadata), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.export_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_export_metadata_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ExportMetadataRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_metadata), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.export_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + metastore.RestoreServiceRequest, + dict, +]) +def test_restore_service(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.restore_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.RestoreServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_restore_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + client.restore_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.RestoreServiceRequest() + +@pytest.mark.asyncio +async def test_restore_service_async(transport: str = 'grpc_asyncio', request_type=metastore.RestoreServiceRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.restore_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.RestoreServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_restore_service_async_from_dict(): + await test_restore_service_async(request_type=dict) + + +def test_restore_service_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.RestoreServiceRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.restore_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_restore_service_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.RestoreServiceRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.restore_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +def test_restore_service_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.restore_service( + service='service_value', + backup='backup_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].service + mock_val = 'service_value' + assert arg == mock_val + arg = args[0].backup + mock_val = 'backup_value' + assert arg == mock_val + + +def test_restore_service_flattened_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restore_service( + metastore.RestoreServiceRequest(), + service='service_value', + backup='backup_value', + ) + +@pytest.mark.asyncio +async def test_restore_service_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.restore_service( + service='service_value', + backup='backup_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].service + mock_val = 'service_value' + assert arg == mock_val + arg = args[0].backup + mock_val = 'backup_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_restore_service_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.restore_service( + metastore.RestoreServiceRequest(), + service='service_value', + backup='backup_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ListBackupsRequest, + dict, +]) +def test_list_backups(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListBackupsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListBackupsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_backups_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_backups), + '__call__') as call: + client.list_backups() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListBackupsRequest() + +@pytest.mark.asyncio +async def test_list_backups_async(transport: str = 'grpc_asyncio', request_type=metastore.ListBackupsRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListBackupsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.ListBackupsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_backups_async_from_dict(): + await test_list_backups_async(request_type=dict) + + +def test_list_backups_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ListBackupsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), + '__call__') as call: + call.return_value = metastore.ListBackupsResponse() + client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backups_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.ListBackupsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListBackupsResponse()) + await client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backups_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListBackupsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_backups( + 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_backups_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_backups( + metastore.ListBackupsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_backups_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.ListBackupsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.ListBackupsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_backups( + 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_backups_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_backups( + metastore.ListBackupsRequest(), + parent='parent_value', + ) + + +def test_list_backups_pager(transport_name: str = "grpc"): + client = DataprocMetastoreClient( + 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_backups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + metastore.Backup(), + ], + next_page_token='abc', + ), + metastore.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + ], + next_page_token='ghi', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_backups(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore.Backup) + for i in results) +def test_list_backups_pages(transport_name: str = "grpc"): + client = DataprocMetastoreClient( + 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_backups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + metastore.Backup(), + ], + next_page_token='abc', + ), + metastore.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + ], + next_page_token='ghi', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + ], + ), + RuntimeError, + ) + pages = list(client.list_backups(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_backups_async_pager(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + metastore.Backup(), + ], + next_page_token='abc', + ), + metastore.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + ], + next_page_token='ghi', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_backups(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, metastore.Backup) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_backups_async_pages(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + metastore.Backup(), + ], + next_page_token='abc', + ), + metastore.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + ], + next_page_token='ghi', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_backups(request={})).pages: # pragma: no branch + 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", [ + metastore.GetBackupRequest, + dict, +]) +def test_get_backup(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.Backup( + name='name_value', + state=metastore.Backup.State.CREATING, + description='description_value', + restoring_services=['restoring_services_value'], + ) + response = client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.Backup) + assert response.name == 'name_value' + assert response.state == metastore.Backup.State.CREATING + assert response.description == 'description_value' + assert response.restoring_services == ['restoring_services_value'] + + +def test_get_backup_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_backup), + '__call__') as call: + client.get_backup() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetBackupRequest() + +@pytest.mark.asyncio +async def test_get_backup_async(transport: str = 'grpc_asyncio', request_type=metastore.GetBackupRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.Backup( + name='name_value', + state=metastore.Backup.State.CREATING, + description='description_value', + restoring_services=['restoring_services_value'], + )) + response = await client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.GetBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.Backup) + assert response.name == 'name_value' + assert response.state == metastore.Backup.State.CREATING + assert response.description == 'description_value' + assert response.restoring_services == ['restoring_services_value'] + + +@pytest.mark.asyncio +async def test_get_backup_async_from_dict(): + await test_get_backup_async(request_type=dict) + + +def test_get_backup_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.GetBackupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup), + '__call__') as call: + call.return_value = metastore.Backup() + client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backup_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.GetBackupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.Backup()) + await client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backup_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.Backup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_backup( + 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_backup_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_backup( + metastore.GetBackupRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_backup_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.Backup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.Backup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_backup( + 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_backup_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_backup( + metastore.GetBackupRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.CreateBackupRequest, + dict, +]) +def test_create_backup(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_backup_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_backup), + '__call__') as call: + client.create_backup() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateBackupRequest() + +@pytest.mark.asyncio +async def test_create_backup_async(transport: str = 'grpc_asyncio', request_type=metastore.CreateBackupRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.CreateBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_backup_async_from_dict(): + await test_create_backup_async(request_type=dict) + + +def test_create_backup_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.CreateBackupRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backup_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.CreateBackupRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backup_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_backup( + parent='parent_value', + backup=metastore.Backup(name='name_value'), + backup_id='backup_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].backup + mock_val = metastore.Backup(name='name_value') + assert arg == mock_val + arg = args[0].backup_id + mock_val = 'backup_id_value' + assert arg == mock_val + + +def test_create_backup_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_backup( + metastore.CreateBackupRequest(), + parent='parent_value', + backup=metastore.Backup(name='name_value'), + backup_id='backup_id_value', + ) + +@pytest.mark.asyncio +async def test_create_backup_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_backup( + parent='parent_value', + backup=metastore.Backup(name='name_value'), + backup_id='backup_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].backup + mock_val = metastore.Backup(name='name_value') + assert arg == mock_val + arg = args[0].backup_id + mock_val = 'backup_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_backup_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_backup( + metastore.CreateBackupRequest(), + parent='parent_value', + backup=metastore.Backup(name='name_value'), + backup_id='backup_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.DeleteBackupRequest, + dict, +]) +def test_delete_backup(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.DeleteBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_backup_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=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_backup), + '__call__') as call: + client.delete_backup() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.DeleteBackupRequest() + +@pytest.mark.asyncio +async def test_delete_backup_async(transport: str = 'grpc_asyncio', request_type=metastore.DeleteBackupRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.DeleteBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_backup_async_from_dict(): + await test_delete_backup_async(request_type=dict) + + +def test_delete_backup_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.DeleteBackupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backup_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.DeleteBackupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_backup_flattened(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_backup( + 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_backup_flattened_error(): + client = DataprocMetastoreClient( + credentials=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_backup( + metastore.DeleteBackupRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_backup_flattened_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_backup( + 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_backup_flattened_error_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_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_backup( + metastore.DeleteBackupRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.RemoveIamPolicyRequest, + dict, +]) +def test_remove_iam_policy(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore.RemoveIamPolicyResponse( + success=True, + ) + response = client.remove_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.RemoveIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.RemoveIamPolicyResponse) + assert response.success is True + + +def test_remove_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_iam_policy), + '__call__') as call: + client.remove_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.RemoveIamPolicyRequest() + +@pytest.mark.asyncio +async def test_remove_iam_policy_async(transport: str = 'grpc_asyncio', request_type=metastore.RemoveIamPolicyRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore.RemoveIamPolicyResponse( + success=True, + )) + response = await client.remove_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.RemoveIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.RemoveIamPolicyResponse) + assert response.success is True + + +@pytest.mark.asyncio +async def test_remove_iam_policy_async_from_dict(): + await test_remove_iam_policy_async(request_type=dict) + + +def test_remove_iam_policy_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.RemoveIamPolicyRequest() + + request.resource = 'resource_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_iam_policy), + '__call__') as call: + call.return_value = metastore.RemoveIamPolicyResponse() + client.remove_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_iam_policy_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.RemoveIamPolicyRequest() + + request.resource = 'resource_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_iam_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore.RemoveIamPolicyResponse()) + await client.remove_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + metastore.QueryMetadataRequest, + dict, +]) +def test_query_metadata(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.query_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.QueryMetadataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_query_metadata_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_metadata), + '__call__') as call: + client.query_metadata() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.QueryMetadataRequest() + +@pytest.mark.asyncio +async def test_query_metadata_async(transport: str = 'grpc_asyncio', request_type=metastore.QueryMetadataRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_metadata), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.query_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.QueryMetadataRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_query_metadata_async_from_dict(): + await test_query_metadata_async(request_type=dict) + + +def test_query_metadata_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.QueryMetadataRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_metadata), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.query_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_query_metadata_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.QueryMetadataRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_metadata), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.query_metadata(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + metastore.MoveTableToDatabaseRequest, + dict, +]) +def test_move_table_to_database(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_table_to_database), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.move_table_to_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.MoveTableToDatabaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_move_table_to_database_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_table_to_database), + '__call__') as call: + client.move_table_to_database() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.MoveTableToDatabaseRequest() + +@pytest.mark.asyncio +async def test_move_table_to_database_async(transport: str = 'grpc_asyncio', request_type=metastore.MoveTableToDatabaseRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_table_to_database), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.move_table_to_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.MoveTableToDatabaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_move_table_to_database_async_from_dict(): + await test_move_table_to_database_async(request_type=dict) + + +def test_move_table_to_database_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.MoveTableToDatabaseRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_table_to_database), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.move_table_to_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_move_table_to_database_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.MoveTableToDatabaseRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_table_to_database), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.move_table_to_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + metastore.AlterMetadataResourceLocationRequest, + dict, +]) +def test_alter_metadata_resource_location(request_type, transport: str = 'grpc'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.alter_metadata_resource_location), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.alter_metadata_resource_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] == metastore.AlterMetadataResourceLocationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_alter_metadata_resource_location_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.alter_metadata_resource_location), + '__call__') as call: + client.alter_metadata_resource_location() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.AlterMetadataResourceLocationRequest() + +@pytest.mark.asyncio +async def test_alter_metadata_resource_location_async(transport: str = 'grpc_asyncio', request_type=metastore.AlterMetadataResourceLocationRequest): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.alter_metadata_resource_location), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.alter_metadata_resource_location(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore.AlterMetadataResourceLocationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_alter_metadata_resource_location_async_from_dict(): + await test_alter_metadata_resource_location_async(request_type=dict) + + +def test_alter_metadata_resource_location_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.AlterMetadataResourceLocationRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.alter_metadata_resource_location), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.alter_metadata_resource_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', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_alter_metadata_resource_location_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore.AlterMetadataResourceLocationRequest() + + request.service = 'service_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.alter_metadata_resource_location), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.alter_metadata_resource_location(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'service=service_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + metastore.ListServicesRequest, + dict, +]) +def test_list_services_rest(request_type): + client = DataprocMetastoreClient( + 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 = metastore.ListServicesResponse( + 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 = metastore.ListServicesResponse.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_services(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_services_rest_required_fields(request_type=metastore.ListServicesRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_services._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_services._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.ListServicesResponse() + # 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 = metastore.ListServicesResponse.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_services(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_services_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_services._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_services_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_list_services") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_list_services") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.ListServicesRequest.pb(metastore.ListServicesRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.ListServicesResponse.to_json(metastore.ListServicesResponse()) + + request = metastore.ListServicesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.ListServicesResponse() + + client.list_services(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_services_rest_bad_request(transport: str = 'rest', request_type=metastore.ListServicesRequest): + client = DataprocMetastoreClient( + 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_services(request) + + +def test_list_services_rest_flattened(): + client = DataprocMetastoreClient( + 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 = metastore.ListServicesResponse() + + # 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 = metastore.ListServicesResponse.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_services(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*}/services" % client.transport._host, args[1]) + + +def test_list_services_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_services( + metastore.ListServicesRequest(), + parent='parent_value', + ) + + +def test_list_services_rest_pager(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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 = ( + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + metastore.Service(), + ], + next_page_token='abc', + ), + metastore.ListServicesResponse( + services=[], + next_page_token='def', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + ], + next_page_token='ghi', + ), + metastore.ListServicesResponse( + services=[ + metastore.Service(), + metastore.Service(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(metastore.ListServicesResponse.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_services(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore.Service) + for i in results) + + pages = list(client.list_services(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", [ + metastore.GetServiceRequest, + dict, +]) +def test_get_service_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/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 = metastore.Service( + name='name_value', + network='network_value', + endpoint_uri='endpoint_uri_value', + port=453, + state=metastore.Service.State.CREATING, + state_message='state_message_value', + artifact_gcs_uri='artifact_gcs_uri_value', + tier=metastore.Service.Tier.DEVELOPER, + uid='uid_value', + release_channel=metastore.Service.ReleaseChannel.CANARY, + database_type=metastore.Service.DatabaseType.MYSQL, + hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value'), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = metastore.Service.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_service(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.Service) + assert response.name == 'name_value' + assert response.network == 'network_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.port == 453 + assert response.state == metastore.Service.State.CREATING + assert response.state_message == 'state_message_value' + assert response.artifact_gcs_uri == 'artifact_gcs_uri_value' + assert response.tier == metastore.Service.Tier.DEVELOPER + assert response.uid == 'uid_value' + assert response.release_channel == metastore.Service.ReleaseChannel.CANARY + assert response.database_type == metastore.Service.DatabaseType.MYSQL + + +def test_get_service_rest_required_fields(request_type=metastore.GetServiceRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_service._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_service._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.Service() + # 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 = metastore.Service.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_service(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_service_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_service_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_get_service") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_get_service") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.GetServiceRequest.pb(metastore.GetServiceRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.Service.to_json(metastore.Service()) + + request = metastore.GetServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.Service() + + client.get_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_service_rest_bad_request(transport: str = 'rest', request_type=metastore.GetServiceRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/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_service(request) + + +def test_get_service_rest_flattened(): + client = DataprocMetastoreClient( + 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 = metastore.Service() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/services/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 = metastore.Service.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_service(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/services/*}" % client.transport._host, args[1]) + + +def test_get_service_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_service( + metastore.GetServiceRequest(), + name='name_value', + ) + + +def test_get_service_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.CreateServiceRequest, + dict, +]) +def test_create_service_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["service"] = {'hive_metastore_config': {'version': 'version_value', 'config_overrides': {}, 'kerberos_config': {'keytab': {'cloud_secret': 'cloud_secret_value'}, 'principal': 'principal_value', 'krb5_config_gcs_uri': 'krb5_config_gcs_uri_value'}, 'endpoint_protocol': 1, 'auxiliary_versions': {}}, 'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'network': 'network_value', 'endpoint_uri': 'endpoint_uri_value', 'port': 453, 'state': 1, 'state_message': 'state_message_value', 'artifact_gcs_uri': 'artifact_gcs_uri_value', 'tier': 1, 'metadata_integration': {'data_catalog_config': {'enabled': True}, 'dataplex_config': {'lake_resources': {}}}, 'maintenance_window': {'hour_of_day': {'value': 541}, 'day_of_week': 1}, 'uid': 'uid_value', 'metadata_management_activity': {'metadata_exports': [{'destination_gcs_uri': 'destination_gcs_uri_value', 'start_time': {}, 'end_time': {}, 'state': 1, 'database_dump_type': 1}], 'restores': [{'start_time': {}, 'end_time': {}, 'state': 1, 'backup': 'backup_value', 'type_': 1, 'details': 'details_value'}]}, 'release_channel': 1, 'encryption_config': {'kms_key': 'kms_key_value'}, 'network_config': {'consumers': [{'subnetwork': 'subnetwork_value', 'endpoint_uri': 'endpoint_uri_value'}]}, 'database_type': 1, 'telemetry_config': {'log_format': 1}} + request = request_type(**request_init) + + # Mock the http request call within the method and 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(name='operations/spam') + + # 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.create_service(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_service_rest_required_fields(request_type=metastore.CreateServiceRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["service_id"] = "" + 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 + assert "serviceId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "serviceId" in jsonified_request + assert jsonified_request["serviceId"] == request_init["service_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["serviceId"] = 'service_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_service._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", "service_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "serviceId" in jsonified_request + assert jsonified_request["serviceId"] == 'service_id_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_service(request) + + expected_params = [ + ( + "serviceId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_service_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "serviceId", )) & set(("parent", "serviceId", "service", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_service_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_create_service") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_create_service") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.CreateServiceRequest.pb(metastore.CreateServiceRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.CreateServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_service_rest_bad_request(transport: str = 'rest', request_type=metastore.CreateServiceRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["service"] = {'hive_metastore_config': {'version': 'version_value', 'config_overrides': {}, 'kerberos_config': {'keytab': {'cloud_secret': 'cloud_secret_value'}, 'principal': 'principal_value', 'krb5_config_gcs_uri': 'krb5_config_gcs_uri_value'}, 'endpoint_protocol': 1, 'auxiliary_versions': {}}, 'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'network': 'network_value', 'endpoint_uri': 'endpoint_uri_value', 'port': 453, 'state': 1, 'state_message': 'state_message_value', 'artifact_gcs_uri': 'artifact_gcs_uri_value', 'tier': 1, 'metadata_integration': {'data_catalog_config': {'enabled': True}, 'dataplex_config': {'lake_resources': {}}}, 'maintenance_window': {'hour_of_day': {'value': 541}, 'day_of_week': 1}, 'uid': 'uid_value', 'metadata_management_activity': {'metadata_exports': [{'destination_gcs_uri': 'destination_gcs_uri_value', 'start_time': {}, 'end_time': {}, 'state': 1, 'database_dump_type': 1}], 'restores': [{'start_time': {}, 'end_time': {}, 'state': 1, 'backup': 'backup_value', 'type_': 1, 'details': 'details_value'}]}, 'release_channel': 1, 'encryption_config': {'kms_key': 'kms_key_value'}, 'network_config': {'consumers': [{'subnetwork': 'subnetwork_value', 'endpoint_uri': 'endpoint_uri_value'}]}, 'database_type': 1, 'telemetry_config': {'log_format': 1}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_service(request) + + +def test_create_service_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # 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', + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + service_id='service_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_service(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*}/services" % client.transport._host, args[1]) + + +def test_create_service_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_service( + metastore.CreateServiceRequest(), + parent='parent_value', + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + service_id='service_id_value', + ) + + +def test_create_service_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.UpdateServiceRequest, + dict, +]) +def test_update_service_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service': {'name': 'projects/sample1/locations/sample2/services/sample3'}} + request_init["service"] = {'hive_metastore_config': {'version': 'version_value', 'config_overrides': {}, 'kerberos_config': {'keytab': {'cloud_secret': 'cloud_secret_value'}, 'principal': 'principal_value', 'krb5_config_gcs_uri': 'krb5_config_gcs_uri_value'}, 'endpoint_protocol': 1, 'auxiliary_versions': {}}, 'name': 'projects/sample1/locations/sample2/services/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'network': 'network_value', 'endpoint_uri': 'endpoint_uri_value', 'port': 453, 'state': 1, 'state_message': 'state_message_value', 'artifact_gcs_uri': 'artifact_gcs_uri_value', 'tier': 1, 'metadata_integration': {'data_catalog_config': {'enabled': True}, 'dataplex_config': {'lake_resources': {}}}, 'maintenance_window': {'hour_of_day': {'value': 541}, 'day_of_week': 1}, 'uid': 'uid_value', 'metadata_management_activity': {'metadata_exports': [{'destination_gcs_uri': 'destination_gcs_uri_value', 'start_time': {}, 'end_time': {}, 'state': 1, 'database_dump_type': 1}], 'restores': [{'start_time': {}, 'end_time': {}, 'state': 1, 'backup': 'backup_value', 'type_': 1, 'details': 'details_value'}]}, 'release_channel': 1, 'encryption_config': {'kms_key': 'kms_key_value'}, 'network_config': {'consumers': [{'subnetwork': 'subnetwork_value', 'endpoint_uri': 'endpoint_uri_value'}]}, 'database_type': 1, 'telemetry_config': {'log_format': 1}} + request = request_type(**request_init) + + # Mock the http request call within the method and 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(name='operations/spam') + + # 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.update_service(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_service_rest_required_fields(request_type=metastore.UpdateServiceRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_service._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_service._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_service(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_service_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "service", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_service_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_update_service") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_update_service") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.UpdateServiceRequest.pb(metastore.UpdateServiceRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.UpdateServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_service_rest_bad_request(transport: str = 'rest', request_type=metastore.UpdateServiceRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service': {'name': 'projects/sample1/locations/sample2/services/sample3'}} + request_init["service"] = {'hive_metastore_config': {'version': 'version_value', 'config_overrides': {}, 'kerberos_config': {'keytab': {'cloud_secret': 'cloud_secret_value'}, 'principal': 'principal_value', 'krb5_config_gcs_uri': 'krb5_config_gcs_uri_value'}, 'endpoint_protocol': 1, 'auxiliary_versions': {}}, 'name': 'projects/sample1/locations/sample2/services/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'network': 'network_value', 'endpoint_uri': 'endpoint_uri_value', 'port': 453, 'state': 1, 'state_message': 'state_message_value', 'artifact_gcs_uri': 'artifact_gcs_uri_value', 'tier': 1, 'metadata_integration': {'data_catalog_config': {'enabled': True}, 'dataplex_config': {'lake_resources': {}}}, 'maintenance_window': {'hour_of_day': {'value': 541}, 'day_of_week': 1}, 'uid': 'uid_value', 'metadata_management_activity': {'metadata_exports': [{'destination_gcs_uri': 'destination_gcs_uri_value', 'start_time': {}, 'end_time': {}, 'state': 1, 'database_dump_type': 1}], 'restores': [{'start_time': {}, 'end_time': {}, 'state': 1, 'backup': 'backup_value', 'type_': 1, 'details': 'details_value'}]}, 'release_channel': 1, 'encryption_config': {'kms_key': 'kms_key_value'}, 'network_config': {'consumers': [{'subnetwork': 'subnetwork_value', 'endpoint_uri': 'endpoint_uri_value'}]}, 'database_type': 1, 'telemetry_config': {'log_format': 1}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_service(request) + + +def test_update_service_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'service': {'name': 'projects/sample1/locations/sample2/services/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_service(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{service.name=projects/*/locations/*/services/*}" % client.transport._host, args[1]) + + +def test_update_service_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_service( + metastore.UpdateServiceRequest(), + service=metastore.Service(hive_metastore_config=metastore.HiveMetastoreConfig(version='version_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_service_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.DeleteServiceRequest, + dict, +]) +def test_delete_service_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/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(name='operations/spam') + + # 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.delete_service(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_service_rest_required_fields(request_type=metastore.DeleteServiceRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_service._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_service._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 "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # 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 = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_service(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_service_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_service_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_delete_service") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_delete_service") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.DeleteServiceRequest.pb(metastore.DeleteServiceRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.DeleteServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_service_rest_bad_request(transport: str = 'rest', request_type=metastore.DeleteServiceRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/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_service(request) + + +def test_delete_service_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/services/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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_service(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/services/*}" % client.transport._host, args[1]) + + +def test_delete_service_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_service( + metastore.DeleteServiceRequest(), + name='name_value', + ) + + +def test_delete_service_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ListMetadataImportsRequest, + dict, +]) +def test_list_metadata_imports_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/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 = metastore.ListMetadataImportsResponse( + 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 = metastore.ListMetadataImportsResponse.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_metadata_imports(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMetadataImportsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_metadata_imports_rest_required_fields(request_type=metastore.ListMetadataImportsRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_metadata_imports._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_metadata_imports._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.ListMetadataImportsResponse() + # 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 = metastore.ListMetadataImportsResponse.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_metadata_imports(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_metadata_imports_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_metadata_imports._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_metadata_imports_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_list_metadata_imports") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_list_metadata_imports") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.ListMetadataImportsRequest.pb(metastore.ListMetadataImportsRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.ListMetadataImportsResponse.to_json(metastore.ListMetadataImportsResponse()) + + request = metastore.ListMetadataImportsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.ListMetadataImportsResponse() + + client.list_metadata_imports(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_metadata_imports_rest_bad_request(transport: str = 'rest', request_type=metastore.ListMetadataImportsRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/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_metadata_imports(request) + + +def test_list_metadata_imports_rest_flattened(): + client = DataprocMetastoreClient( + 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 = metastore.ListMetadataImportsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/services/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 = metastore.ListMetadataImportsResponse.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_metadata_imports(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/services/*}/metadataImports" % client.transport._host, args[1]) + + +def test_list_metadata_imports_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_metadata_imports( + metastore.ListMetadataImportsRequest(), + parent='parent_value', + ) + + +def test_list_metadata_imports_rest_pager(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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 = ( + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + next_page_token='abc', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[], + next_page_token='def', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + ], + next_page_token='ghi', + ), + metastore.ListMetadataImportsResponse( + metadata_imports=[ + metastore.MetadataImport(), + metastore.MetadataImport(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(metastore.ListMetadataImportsResponse.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/services/sample3'} + + pager = client.list_metadata_imports(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore.MetadataImport) + for i in results) + + pages = list(client.list_metadata_imports(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", [ + metastore.GetMetadataImportRequest, + dict, +]) +def test_get_metadata_import_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/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 = metastore.MetadataImport( + name='name_value', + description='description_value', + state=metastore.MetadataImport.State.RUNNING, + database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = metastore.MetadataImport.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_metadata_import(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.MetadataImport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.state == metastore.MetadataImport.State.RUNNING + + +def test_get_metadata_import_rest_required_fields(request_type=metastore.GetMetadataImportRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_metadata_import._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_metadata_import._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.MetadataImport() + # 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 = metastore.MetadataImport.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_metadata_import(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_metadata_import_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_metadata_import._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_metadata_import_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_get_metadata_import") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_get_metadata_import") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.GetMetadataImportRequest.pb(metastore.GetMetadataImportRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.MetadataImport.to_json(metastore.MetadataImport()) + + request = metastore.GetMetadataImportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.MetadataImport() + + client.get_metadata_import(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_metadata_import_rest_bad_request(transport: str = 'rest', request_type=metastore.GetMetadataImportRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/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_metadata_import(request) + + +def test_get_metadata_import_rest_flattened(): + client = DataprocMetastoreClient( + 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 = metastore.MetadataImport() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/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 = metastore.MetadataImport.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_metadata_import(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/services/*/metadataImports/*}" % client.transport._host, args[1]) + + +def test_get_metadata_import_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_metadata_import( + metastore.GetMetadataImportRequest(), + name='name_value', + ) + + +def test_get_metadata_import_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.CreateMetadataImportRequest, + dict, +]) +def test_create_metadata_import_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/sample3'} + request_init["metadata_import"] = {'database_dump': {'database_type': 1, 'gcs_uri': 'gcs_uri_value', 'source_database': 'source_database_value', 'type_': 1}, 'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'end_time': {}, 'state': 1} + request = request_type(**request_init) + + # Mock the http request call within the method and 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(name='operations/spam') + + # 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.create_metadata_import(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_metadata_import_rest_required_fields(request_type=metastore.CreateMetadataImportRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["metadata_import_id"] = "" + 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 + assert "metadataImportId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_metadata_import._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "metadataImportId" in jsonified_request + assert jsonified_request["metadataImportId"] == request_init["metadata_import_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["metadataImportId"] = 'metadata_import_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_metadata_import._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("metadata_import_id", "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' + assert "metadataImportId" in jsonified_request + assert jsonified_request["metadataImportId"] == 'metadata_import_id_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_metadata_import(request) + + expected_params = [ + ( + "metadataImportId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_metadata_import_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_metadata_import._get_unset_required_fields({}) + assert set(unset_fields) == (set(("metadataImportId", "requestId", )) & set(("parent", "metadataImportId", "metadataImport", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_metadata_import_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_create_metadata_import") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_create_metadata_import") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.CreateMetadataImportRequest.pb(metastore.CreateMetadataImportRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.CreateMetadataImportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_metadata_import(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_metadata_import_rest_bad_request(transport: str = 'rest', request_type=metastore.CreateMetadataImportRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/sample3'} + request_init["metadata_import"] = {'database_dump': {'database_type': 1, 'gcs_uri': 'gcs_uri_value', 'source_database': 'source_database_value', 'type_': 1}, 'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'end_time': {}, 'state': 1} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_metadata_import(request) + + +def test_create_metadata_import_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/services/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + metadata_import_id='metadata_import_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_metadata_import(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/services/*}/metadataImports" % client.transport._host, args[1]) + + +def test_create_metadata_import_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_metadata_import( + metastore.CreateMetadataImportRequest(), + parent='parent_value', + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + metadata_import_id='metadata_import_id_value', + ) + + +def test_create_metadata_import_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.UpdateMetadataImportRequest, + dict, +]) +def test_update_metadata_import_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'metadata_import': {'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/sample4'}} + request_init["metadata_import"] = {'database_dump': {'database_type': 1, 'gcs_uri': 'gcs_uri_value', 'source_database': 'source_database_value', 'type_': 1}, 'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/sample4', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'end_time': {}, 'state': 1} + request = request_type(**request_init) + + # Mock the http request call within the method and 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(name='operations/spam') + + # 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.update_metadata_import(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_metadata_import_rest_required_fields(request_type=metastore.UpdateMetadataImportRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_metadata_import._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_metadata_import._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_metadata_import(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_metadata_import_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_metadata_import._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "metadataImport", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_metadata_import_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_update_metadata_import") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_update_metadata_import") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.UpdateMetadataImportRequest.pb(metastore.UpdateMetadataImportRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.UpdateMetadataImportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_metadata_import(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_metadata_import_rest_bad_request(transport: str = 'rest', request_type=metastore.UpdateMetadataImportRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'metadata_import': {'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/sample4'}} + request_init["metadata_import"] = {'database_dump': {'database_type': 1, 'gcs_uri': 'gcs_uri_value', 'source_database': 'source_database_value', 'type_': 1}, 'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/sample4', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'end_time': {}, 'state': 1} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_metadata_import(request) + + +def test_update_metadata_import_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'metadata_import': {'name': 'projects/sample1/locations/sample2/services/sample3/metadataImports/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + 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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_metadata_import(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{metadata_import.name=projects/*/locations/*/services/*/metadataImports/*}" % client.transport._host, args[1]) + + +def test_update_metadata_import_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_metadata_import( + metastore.UpdateMetadataImportRequest(), + metadata_import=metastore.MetadataImport(database_dump=metastore.MetadataImport.DatabaseDump(database_type=metastore.MetadataImport.DatabaseDump.DatabaseType.MYSQL)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_metadata_import_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ExportMetadataRequest, + dict, +]) +def test_export_metadata_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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(name='operations/spam') + + # 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.export_metadata(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_export_metadata_rest_required_fields(request_type=metastore.ExportMetadataRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["service"] = "" + 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()).export_metadata._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["service"] = 'service_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_metadata._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "service" in jsonified_request + assert jsonified_request["service"] == 'service_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.export_metadata(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_export_metadata_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.export_metadata._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("service", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_metadata_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_export_metadata") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_export_metadata") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.ExportMetadataRequest.pb(metastore.ExportMetadataRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.ExportMetadataRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.export_metadata(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_export_metadata_rest_bad_request(transport: str = 'rest', request_type=metastore.ExportMetadataRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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.export_metadata(request) + + +def test_export_metadata_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.RestoreServiceRequest, + dict, +]) +def test_restore_service_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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(name='operations/spam') + + # 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.restore_service(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_restore_service_rest_required_fields(request_type=metastore.RestoreServiceRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["service"] = "" + request_init["backup"] = "" + 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()).restore_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["service"] = 'service_value' + jsonified_request["backup"] = 'backup_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).restore_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "service" in jsonified_request + assert jsonified_request["service"] == 'service_value' + assert "backup" in jsonified_request + assert jsonified_request["backup"] == 'backup_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.restore_service(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_restore_service_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.restore_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("service", "backup", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_restore_service_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_restore_service") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_restore_service") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.RestoreServiceRequest.pb(metastore.RestoreServiceRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.RestoreServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.restore_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_restore_service_rest_bad_request(transport: str = 'rest', request_type=metastore.RestoreServiceRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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.restore_service(request) + + +def test_restore_service_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'service': 'projects/sample1/locations/sample2/services/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + service='service_value', + backup='backup_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.restore_service(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{service=projects/*/locations/*/services/*}:restore" % client.transport._host, args[1]) + + +def test_restore_service_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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.restore_service( + metastore.RestoreServiceRequest(), + service='service_value', + backup='backup_value', + ) + + +def test_restore_service_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.ListBackupsRequest, + dict, +]) +def test_list_backups_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/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 = metastore.ListBackupsResponse( + 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 = metastore.ListBackupsResponse.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_backups(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_backups_rest_required_fields(request_type=metastore.ListBackupsRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_backups._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_backups._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.ListBackupsResponse() + # 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 = metastore.ListBackupsResponse.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_backups(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_backups_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_backups._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_backups_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_list_backups") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_list_backups") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.ListBackupsRequest.pb(metastore.ListBackupsRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.ListBackupsResponse.to_json(metastore.ListBackupsResponse()) + + request = metastore.ListBackupsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.ListBackupsResponse() + + client.list_backups(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_backups_rest_bad_request(transport: str = 'rest', request_type=metastore.ListBackupsRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/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_backups(request) + + +def test_list_backups_rest_flattened(): + client = DataprocMetastoreClient( + 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 = metastore.ListBackupsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/services/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 = metastore.ListBackupsResponse.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_backups(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/services/*}/backups" % client.transport._host, args[1]) + + +def test_list_backups_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_backups( + metastore.ListBackupsRequest(), + parent='parent_value', + ) + + +def test_list_backups_rest_pager(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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 = ( + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + metastore.Backup(), + ], + next_page_token='abc', + ), + metastore.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + ], + next_page_token='ghi', + ), + metastore.ListBackupsResponse( + backups=[ + metastore.Backup(), + metastore.Backup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(metastore.ListBackupsResponse.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/services/sample3'} + + pager = client.list_backups(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore.Backup) + for i in results) + + pages = list(client.list_backups(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", [ + metastore.GetBackupRequest, + dict, +]) +def test_get_backup_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/sample3/backups/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 = metastore.Backup( + name='name_value', + state=metastore.Backup.State.CREATING, + description='description_value', + restoring_services=['restoring_services_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = metastore.Backup.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_backup(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.Backup) + assert response.name == 'name_value' + assert response.state == metastore.Backup.State.CREATING + assert response.description == 'description_value' + assert response.restoring_services == ['restoring_services_value'] + + +def test_get_backup_rest_required_fields(request_type=metastore.GetBackupRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_backup._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_backup._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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.Backup() + # 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 = metastore.Backup.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_backup(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_backup_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_backup_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_get_backup") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_get_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.GetBackupRequest.pb(metastore.GetBackupRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.Backup.to_json(metastore.Backup()) + + request = metastore.GetBackupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.Backup() + + client.get_backup(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_backup_rest_bad_request(transport: str = 'rest', request_type=metastore.GetBackupRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/sample3/backups/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_backup(request) + + +def test_get_backup_rest_flattened(): + client = DataprocMetastoreClient( + 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 = metastore.Backup() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/services/sample3/backups/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 = metastore.Backup.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_backup(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/services/*/backups/*}" % client.transport._host, args[1]) + + +def test_get_backup_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_backup( + metastore.GetBackupRequest(), + name='name_value', + ) + + +def test_get_backup_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.CreateBackupRequest, + dict, +]) +def test_create_backup_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/sample3'} + request_init["backup"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}, 'state': 1, 'service_revision': {'hive_metastore_config': {'version': 'version_value', 'config_overrides': {}, 'kerberos_config': {'keytab': {'cloud_secret': 'cloud_secret_value'}, 'principal': 'principal_value', 'krb5_config_gcs_uri': 'krb5_config_gcs_uri_value'}, 'endpoint_protocol': 1, 'auxiliary_versions': {}}, 'name': 'name_value', 'create_time': {}, 'update_time': {}, 'labels': {}, 'network': 'network_value', 'endpoint_uri': 'endpoint_uri_value', 'port': 453, 'state': 1, 'state_message': 'state_message_value', 'artifact_gcs_uri': 'artifact_gcs_uri_value', 'tier': 1, 'metadata_integration': {'data_catalog_config': {'enabled': True}, 'dataplex_config': {'lake_resources': {}}}, 'maintenance_window': {'hour_of_day': {'value': 541}, 'day_of_week': 1}, 'uid': 'uid_value', 'metadata_management_activity': {'metadata_exports': [{'destination_gcs_uri': 'destination_gcs_uri_value', 'start_time': {}, 'end_time': {}, 'state': 1, 'database_dump_type': 1}], 'restores': [{'start_time': {}, 'end_time': {}, 'state': 1, 'backup': 'backup_value', 'type_': 1, 'details': 'details_value'}]}, 'release_channel': 1, 'encryption_config': {'kms_key': 'kms_key_value'}, 'network_config': {'consumers': [{'subnetwork': 'subnetwork_value', 'endpoint_uri': 'endpoint_uri_value'}]}, 'database_type': 1, 'telemetry_config': {'log_format': 1}}, 'description': 'description_value', 'restoring_services': ['restoring_services_value1', 'restoring_services_value2']} + request = request_type(**request_init) + + # Mock the http request call within the method and 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(name='operations/spam') + + # 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.create_backup(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_backup_rest_required_fields(request_type=metastore.CreateBackupRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["backup_id"] = "" + 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 + assert "backupId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_backup._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "backupId" in jsonified_request + assert jsonified_request["backupId"] == request_init["backup_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["backupId"] = 'backup_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_backup._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("backup_id", "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' + assert "backupId" in jsonified_request + assert jsonified_request["backupId"] == 'backup_id_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_backup(request) + + expected_params = [ + ( + "backupId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_backup_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(("backupId", "requestId", )) & set(("parent", "backupId", "backup", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_backup_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_create_backup") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_create_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.CreateBackupRequest.pb(metastore.CreateBackupRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.CreateBackupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_backup(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_backup_rest_bad_request(transport: str = 'rest', request_type=metastore.CreateBackupRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/services/sample3'} + request_init["backup"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}, 'state': 1, 'service_revision': {'hive_metastore_config': {'version': 'version_value', 'config_overrides': {}, 'kerberos_config': {'keytab': {'cloud_secret': 'cloud_secret_value'}, 'principal': 'principal_value', 'krb5_config_gcs_uri': 'krb5_config_gcs_uri_value'}, 'endpoint_protocol': 1, 'auxiliary_versions': {}}, 'name': 'name_value', 'create_time': {}, 'update_time': {}, 'labels': {}, 'network': 'network_value', 'endpoint_uri': 'endpoint_uri_value', 'port': 453, 'state': 1, 'state_message': 'state_message_value', 'artifact_gcs_uri': 'artifact_gcs_uri_value', 'tier': 1, 'metadata_integration': {'data_catalog_config': {'enabled': True}, 'dataplex_config': {'lake_resources': {}}}, 'maintenance_window': {'hour_of_day': {'value': 541}, 'day_of_week': 1}, 'uid': 'uid_value', 'metadata_management_activity': {'metadata_exports': [{'destination_gcs_uri': 'destination_gcs_uri_value', 'start_time': {}, 'end_time': {}, 'state': 1, 'database_dump_type': 1}], 'restores': [{'start_time': {}, 'end_time': {}, 'state': 1, 'backup': 'backup_value', 'type_': 1, 'details': 'details_value'}]}, 'release_channel': 1, 'encryption_config': {'kms_key': 'kms_key_value'}, 'network_config': {'consumers': [{'subnetwork': 'subnetwork_value', 'endpoint_uri': 'endpoint_uri_value'}]}, 'database_type': 1, 'telemetry_config': {'log_format': 1}}, 'description': 'description_value', 'restoring_services': ['restoring_services_value1', 'restoring_services_value2']} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_backup(request) + + +def test_create_backup_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/services/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + backup=metastore.Backup(name='name_value'), + backup_id='backup_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_backup(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/services/*}/backups" % client.transport._host, args[1]) + + +def test_create_backup_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_backup( + metastore.CreateBackupRequest(), + parent='parent_value', + backup=metastore.Backup(name='name_value'), + backup_id='backup_id_value', + ) + + +def test_create_backup_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.DeleteBackupRequest, + dict, +]) +def test_delete_backup_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/sample3/backups/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 = operations_pb2.Operation(name='operations/spam') + + # 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.delete_backup(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_backup_rest_required_fields(request_type=metastore.DeleteBackupRequest): + transport_class = transports.DataprocMetastoreRestTransport + + 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_backup._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_backup._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 "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # 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 = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_backup(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_backup_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_backup_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_delete_backup") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_delete_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.DeleteBackupRequest.pb(metastore.DeleteBackupRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.DeleteBackupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_backup(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_backup_rest_bad_request(transport: str = 'rest', request_type=metastore.DeleteBackupRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/services/sample3/backups/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.delete_backup(request) + + +def test_delete_backup_rest_flattened(): + client = DataprocMetastoreClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/services/sample3/backups/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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_backup(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/services/*/backups/*}" % client.transport._host, args[1]) + + +def test_delete_backup_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreClient( + 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_backup( + metastore.DeleteBackupRequest(), + name='name_value', + ) + + +def test_delete_backup_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.RemoveIamPolicyRequest, + dict, +]) +def test_remove_iam_policy_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'projects/sample1/locations/sample2/services/sample3/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 = metastore.RemoveIamPolicyResponse( + success=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = metastore.RemoveIamPolicyResponse.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.remove_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore.RemoveIamPolicyResponse) + assert response.success is True + + +def test_remove_iam_policy_rest_required_fields(request_type=metastore.RemoveIamPolicyRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["resource"] = "" + 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()).remove_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore.RemoveIamPolicyResponse() + # 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 = metastore.RemoveIamPolicyResponse.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.remove_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_remove_iam_policy_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.remove_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_remove_iam_policy_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_remove_iam_policy") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_remove_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.RemoveIamPolicyRequest.pb(metastore.RemoveIamPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore.RemoveIamPolicyResponse.to_json(metastore.RemoveIamPolicyResponse()) + + request = metastore.RemoveIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore.RemoveIamPolicyResponse() + + client.remove_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_remove_iam_policy_rest_bad_request(transport: str = 'rest', request_type=metastore.RemoveIamPolicyRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'projects/sample1/locations/sample2/services/sample3/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.remove_iam_policy(request) + + +def test_remove_iam_policy_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.QueryMetadataRequest, + dict, +]) +def test_query_metadata_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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(name='operations/spam') + + # 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.query_metadata(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_query_metadata_rest_required_fields(request_type=metastore.QueryMetadataRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["service"] = "" + request_init["query"] = "" + 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()).query_metadata._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["service"] = 'service_value' + jsonified_request["query"] = 'query_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).query_metadata._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "service" in jsonified_request + assert jsonified_request["service"] == 'service_value' + assert "query" in jsonified_request + assert jsonified_request["query"] == 'query_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.query_metadata(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_query_metadata_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.query_metadata._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("service", "query", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_query_metadata_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_query_metadata") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_query_metadata") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.QueryMetadataRequest.pb(metastore.QueryMetadataRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.QueryMetadataRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.query_metadata(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_query_metadata_rest_bad_request(transport: str = 'rest', request_type=metastore.QueryMetadataRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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.query_metadata(request) + + +def test_query_metadata_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.MoveTableToDatabaseRequest, + dict, +]) +def test_move_table_to_database_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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(name='operations/spam') + + # 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.move_table_to_database(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_move_table_to_database_rest_required_fields(request_type=metastore.MoveTableToDatabaseRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["service"] = "" + request_init["table_name"] = "" + request_init["db_name"] = "" + request_init["destination_db_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()).move_table_to_database._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["service"] = 'service_value' + jsonified_request["tableName"] = 'table_name_value' + jsonified_request["dbName"] = 'db_name_value' + jsonified_request["destinationDbName"] = 'destination_db_name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).move_table_to_database._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "service" in jsonified_request + assert jsonified_request["service"] == 'service_value' + assert "tableName" in jsonified_request + assert jsonified_request["tableName"] == 'table_name_value' + assert "dbName" in jsonified_request + assert jsonified_request["dbName"] == 'db_name_value' + assert "destinationDbName" in jsonified_request + assert jsonified_request["destinationDbName"] == 'destination_db_name_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.move_table_to_database(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_move_table_to_database_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.move_table_to_database._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("service", "tableName", "dbName", "destinationDbName", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_move_table_to_database_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_move_table_to_database") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_move_table_to_database") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.MoveTableToDatabaseRequest.pb(metastore.MoveTableToDatabaseRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.MoveTableToDatabaseRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.move_table_to_database(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_move_table_to_database_rest_bad_request(transport: str = 'rest', request_type=metastore.MoveTableToDatabaseRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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.move_table_to_database(request) + + +def test_move_table_to_database_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore.AlterMetadataResourceLocationRequest, + dict, +]) +def test_alter_metadata_resource_location_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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(name='operations/spam') + + # 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.alter_metadata_resource_location(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_alter_metadata_resource_location_rest_required_fields(request_type=metastore.AlterMetadataResourceLocationRequest): + transport_class = transports.DataprocMetastoreRestTransport + + request_init = {} + request_init["service"] = "" + request_init["resource_name"] = "" + request_init["location_uri"] = "" + 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()).alter_metadata_resource_location._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["service"] = 'service_value' + jsonified_request["resourceName"] = 'resource_name_value' + jsonified_request["locationUri"] = 'location_uri_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).alter_metadata_resource_location._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "service" in jsonified_request + assert jsonified_request["service"] == 'service_value' + assert "resourceName" in jsonified_request + assert jsonified_request["resourceName"] == 'resource_name_value' + assert "locationUri" in jsonified_request + assert jsonified_request["locationUri"] == 'location_uri_value' + + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.alter_metadata_resource_location(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_alter_metadata_resource_location_rest_unset_required_fields(): + transport = transports.DataprocMetastoreRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.alter_metadata_resource_location._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("service", "resourceName", "locationUri", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_alter_metadata_resource_location_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreRestInterceptor(), + ) + client = DataprocMetastoreClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "post_alter_metadata_resource_location") as post, \ + mock.patch.object(transports.DataprocMetastoreRestInterceptor, "pre_alter_metadata_resource_location") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore.AlterMetadataResourceLocationRequest.pb(metastore.AlterMetadataResourceLocationRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore.AlterMetadataResourceLocationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.alter_metadata_resource_location(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_alter_metadata_resource_location_rest_bad_request(transport: str = 'rest', request_type=metastore.AlterMetadataResourceLocationRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service': 'projects/sample1/locations/sample2/services/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.alter_metadata_resource_location(request) + + +def test_alter_metadata_resource_location_rest_error(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DataprocMetastoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DataprocMetastoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataprocMetastoreClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DataprocMetastoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DataprocMetastoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataprocMetastoreClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataprocMetastoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DataprocMetastoreClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataprocMetastoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DataprocMetastoreGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DataprocMetastoreGrpcTransport, + transports.DataprocMetastoreGrpcAsyncIOTransport, + transports.DataprocMetastoreRestTransport, +]) +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 = DataprocMetastoreClient.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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DataprocMetastoreGrpcTransport, + ) + +def test_dataproc_metastore_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DataprocMetastoreTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_dataproc_metastore_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.metastore_v1beta.services.dataproc_metastore.transports.DataprocMetastoreTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DataprocMetastoreTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_services', + 'get_service', + 'create_service', + 'update_service', + 'delete_service', + 'list_metadata_imports', + 'get_metadata_import', + 'create_metadata_import', + 'update_metadata_import', + 'export_metadata', + 'restore_service', + 'list_backups', + 'get_backup', + 'create_backup', + 'delete_backup', + 'remove_iam_policy', + 'query_metadata', + 'move_table_to_database', + 'alter_metadata_resource_location', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_dataproc_metastore_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.metastore_v1beta.services.dataproc_metastore.transports.DataprocMetastoreTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataprocMetastoreTransport( + 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_dataproc_metastore_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.metastore_v1beta.services.dataproc_metastore.transports.DataprocMetastoreTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataprocMetastoreTransport() + adc.assert_called_once() + + +def test_dataproc_metastore_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) + DataprocMetastoreClient() + 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.DataprocMetastoreGrpcTransport, + transports.DataprocMetastoreGrpcAsyncIOTransport, + ], +) +def test_dataproc_metastore_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.DataprocMetastoreGrpcTransport, + transports.DataprocMetastoreGrpcAsyncIOTransport, + transports.DataprocMetastoreRestTransport, + ], +) +def test_dataproc_metastore_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.DataprocMetastoreGrpcTransport, grpc_helpers), + (transports.DataprocMetastoreGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_dataproc_metastore_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( + "metastore.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="metastore.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DataprocMetastoreGrpcTransport, transports.DataprocMetastoreGrpcAsyncIOTransport]) +def test_dataproc_metastore_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_dataproc_metastore_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.DataprocMetastoreRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_dataproc_metastore_rest_lro_client(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_dataproc_metastore_host_no_port(transport_name): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='metastore.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'metastore.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://metastore.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_dataproc_metastore_host_with_port(transport_name): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='metastore.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'metastore.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://metastore.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_dataproc_metastore_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DataprocMetastoreClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DataprocMetastoreClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_services._session + session2 = client2.transport.list_services._session + assert session1 != session2 + session1 = client1.transport.get_service._session + session2 = client2.transport.get_service._session + assert session1 != session2 + session1 = client1.transport.create_service._session + session2 = client2.transport.create_service._session + assert session1 != session2 + session1 = client1.transport.update_service._session + session2 = client2.transport.update_service._session + assert session1 != session2 + session1 = client1.transport.delete_service._session + session2 = client2.transport.delete_service._session + assert session1 != session2 + session1 = client1.transport.list_metadata_imports._session + session2 = client2.transport.list_metadata_imports._session + assert session1 != session2 + session1 = client1.transport.get_metadata_import._session + session2 = client2.transport.get_metadata_import._session + assert session1 != session2 + session1 = client1.transport.create_metadata_import._session + session2 = client2.transport.create_metadata_import._session + assert session1 != session2 + session1 = client1.transport.update_metadata_import._session + session2 = client2.transport.update_metadata_import._session + assert session1 != session2 + session1 = client1.transport.export_metadata._session + session2 = client2.transport.export_metadata._session + assert session1 != session2 + session1 = client1.transport.restore_service._session + session2 = client2.transport.restore_service._session + assert session1 != session2 + session1 = client1.transport.list_backups._session + session2 = client2.transport.list_backups._session + assert session1 != session2 + session1 = client1.transport.get_backup._session + session2 = client2.transport.get_backup._session + assert session1 != session2 + session1 = client1.transport.create_backup._session + session2 = client2.transport.create_backup._session + assert session1 != session2 + session1 = client1.transport.delete_backup._session + session2 = client2.transport.delete_backup._session + assert session1 != session2 + session1 = client1.transport.remove_iam_policy._session + session2 = client2.transport.remove_iam_policy._session + assert session1 != session2 + session1 = client1.transport.query_metadata._session + session2 = client2.transport.query_metadata._session + assert session1 != session2 + session1 = client1.transport.move_table_to_database._session + session2 = client2.transport.move_table_to_database._session + assert session1 != session2 + session1 = client1.transport.alter_metadata_resource_location._session + session2 = client2.transport.alter_metadata_resource_location._session + assert session1 != session2 +def test_dataproc_metastore_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataprocMetastoreGrpcTransport( + 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_dataproc_metastore_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataprocMetastoreGrpcAsyncIOTransport( + 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.DataprocMetastoreGrpcTransport, transports.DataprocMetastoreGrpcAsyncIOTransport]) +def test_dataproc_metastore_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.DataprocMetastoreGrpcTransport, transports.DataprocMetastoreGrpcAsyncIOTransport]) +def test_dataproc_metastore_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_dataproc_metastore_grpc_lro_client(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_dataproc_metastore_grpc_lro_async_client(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_backup_path(): + project = "squid" + location = "clam" + service = "whelk" + backup = "octopus" + expected = "projects/{project}/locations/{location}/services/{service}/backups/{backup}".format(project=project, location=location, service=service, backup=backup, ) + actual = DataprocMetastoreClient.backup_path(project, location, service, backup) + assert expected == actual + + +def test_parse_backup_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "service": "cuttlefish", + "backup": "mussel", + } + path = DataprocMetastoreClient.backup_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_backup_path(path) + assert expected == actual + +def test_lake_path(): + project = "winkle" + location = "nautilus" + lake = "scallop" + expected = "projects/{project}/locations/{location}/lakes/{lake}".format(project=project, location=location, lake=lake, ) + actual = DataprocMetastoreClient.lake_path(project, location, lake) + assert expected == actual + + +def test_parse_lake_path(): + expected = { + "project": "abalone", + "location": "squid", + "lake": "clam", + } + path = DataprocMetastoreClient.lake_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_lake_path(path) + assert expected == actual + +def test_metadata_import_path(): + project = "whelk" + location = "octopus" + service = "oyster" + metadata_import = "nudibranch" + expected = "projects/{project}/locations/{location}/services/{service}/metadataImports/{metadata_import}".format(project=project, location=location, service=service, metadata_import=metadata_import, ) + actual = DataprocMetastoreClient.metadata_import_path(project, location, service, metadata_import) + assert expected == actual + + +def test_parse_metadata_import_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "service": "winkle", + "metadata_import": "nautilus", + } + path = DataprocMetastoreClient.metadata_import_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_metadata_import_path(path) + assert expected == actual + +def test_network_path(): + project = "scallop" + network = "abalone" + expected = "projects/{project}/global/networks/{network}".format(project=project, network=network, ) + actual = DataprocMetastoreClient.network_path(project, network) + assert expected == actual + + +def test_parse_network_path(): + expected = { + "project": "squid", + "network": "clam", + } + path = DataprocMetastoreClient.network_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_network_path(path) + assert expected == actual + +def test_service_path(): + project = "whelk" + location = "octopus" + service = "oyster" + expected = "projects/{project}/locations/{location}/services/{service}".format(project=project, location=location, service=service, ) + actual = DataprocMetastoreClient.service_path(project, location, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "service": "mussel", + } + path = DataprocMetastoreClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_service_path(path) + assert expected == actual + +def test_subnetwork_path(): + project = "winkle" + region = "nautilus" + subnetwork = "scallop" + expected = "projects/{project}/regions/{region}/subnetworks/{subnetwork}".format(project=project, region=region, subnetwork=subnetwork, ) + actual = DataprocMetastoreClient.subnetwork_path(project, region, subnetwork) + assert expected == actual + + +def test_parse_subnetwork_path(): + expected = { + "project": "abalone", + "region": "squid", + "subnetwork": "clam", + } + path = DataprocMetastoreClient.subnetwork_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_subnetwork_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DataprocMetastoreClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = DataprocMetastoreClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = DataprocMetastoreClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = DataprocMetastoreClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DataprocMetastoreClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = DataprocMetastoreClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = DataprocMetastoreClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = DataprocMetastoreClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.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 = DataprocMetastoreClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = DataprocMetastoreClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreClient.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.DataprocMetastoreTransport, '_prep_wrapped_messages') as prep: + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DataprocMetastoreTransport, '_prep_wrapped_messages') as prep: + transport_class = DataprocMetastoreClient.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 = DataprocMetastoreAsyncClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/services/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_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/services/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 = policy_pb2.Policy() + + # 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_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/services/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.set_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/services/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 = policy_pb2.Policy() + + # 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.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/services/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.test_iam_permissions(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/services/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 = iam_policy_pb2.TestIamPermissionsResponse() + + # 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.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreAsyncClient( + 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_get_operation(transport: str = "grpc"): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreAsyncClient( + 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreAsyncClient( + 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreAsyncClient( + 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value 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 = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value 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 = DataprocMetastoreClient( + 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 = DataprocMetastoreAsyncClient( + 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_set_iam_policy(transport: str = "grpc"): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the 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, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = DataprocMetastoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = DataprocMetastoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DataprocMetastoreClient( + 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 = DataprocMetastoreClient( + 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", [ + (DataprocMetastoreClient, transports.DataprocMetastoreGrpcTransport), + (DataprocMetastoreAsyncClient, transports.DataprocMetastoreGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v1beta/tests/unit/gapic/metastore_v1beta/test_dataproc_metastore_federation.py b/owl-bot-staging/v1beta/tests/unit/gapic/metastore_v1beta/test_dataproc_metastore_federation.py new file mode 100644 index 0000000..4e05b83 --- /dev/null +++ b/owl-bot-staging/v1beta/tests/unit/gapic/metastore_v1beta/test_dataproc_metastore_federation.py @@ -0,0 +1,5435 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.metastore_v1beta.services.dataproc_metastore_federation import DataprocMetastoreFederationAsyncClient +from google.cloud.metastore_v1beta.services.dataproc_metastore_federation import DataprocMetastoreFederationClient +from google.cloud.metastore_v1beta.services.dataproc_metastore_federation import pagers +from google.cloud.metastore_v1beta.services.dataproc_metastore_federation import transports +from google.cloud.metastore_v1beta.types import metastore +from google.cloud.metastore_v1beta.types import metastore_federation +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DataprocMetastoreFederationClient._get_default_mtls_endpoint(None) is None + assert DataprocMetastoreFederationClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DataprocMetastoreFederationClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DataprocMetastoreFederationClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DataprocMetastoreFederationClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DataprocMetastoreFederationClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DataprocMetastoreFederationClient, "grpc"), + (DataprocMetastoreFederationAsyncClient, "grpc_asyncio"), + (DataprocMetastoreFederationClient, "rest"), +]) +def test_dataproc_metastore_federation_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 == ( + 'metastore.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://metastore.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DataprocMetastoreFederationGrpcTransport, "grpc"), + (transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DataprocMetastoreFederationRestTransport, "rest"), +]) +def test_dataproc_metastore_federation_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", [ + (DataprocMetastoreFederationClient, "grpc"), + (DataprocMetastoreFederationAsyncClient, "grpc_asyncio"), + (DataprocMetastoreFederationClient, "rest"), +]) +def test_dataproc_metastore_federation_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 == ( + 'metastore.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://metastore.googleapis.com' + ) + + +def test_dataproc_metastore_federation_client_get_transport_class(): + transport = DataprocMetastoreFederationClient.get_transport_class() + available_transports = [ + transports.DataprocMetastoreFederationGrpcTransport, + transports.DataprocMetastoreFederationRestTransport, + ] + assert transport in available_transports + + transport = DataprocMetastoreFederationClient.get_transport_class("grpc") + assert transport == transports.DataprocMetastoreFederationGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport, "grpc"), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio"), + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationRestTransport, "rest"), +]) +@mock.patch.object(DataprocMetastoreFederationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreFederationClient)) +@mock.patch.object(DataprocMetastoreFederationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreFederationAsyncClient)) +def test_dataproc_metastore_federation_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(DataprocMetastoreFederationClient, '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(DataprocMetastoreFederationClient, '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", [ + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport, "grpc", "true"), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport, "grpc", "false"), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationRestTransport, "rest", "true"), + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationRestTransport, "rest", "false"), +]) +@mock.patch.object(DataprocMetastoreFederationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreFederationClient)) +@mock.patch.object(DataprocMetastoreFederationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreFederationAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_dataproc_metastore_federation_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", [ + DataprocMetastoreFederationClient, DataprocMetastoreFederationAsyncClient +]) +@mock.patch.object(DataprocMetastoreFederationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreFederationClient)) +@mock.patch.object(DataprocMetastoreFederationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataprocMetastoreFederationAsyncClient)) +def test_dataproc_metastore_federation_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", [ + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport, "grpc"), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio"), + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationRestTransport, "rest"), +]) +def test_dataproc_metastore_federation_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", [ + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport, "grpc", grpc_helpers), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationRestTransport, "rest", None), +]) +def test_dataproc_metastore_federation_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_dataproc_metastore_federation_client_client_options_from_dict(): + with mock.patch('google.cloud.metastore_v1beta.services.dataproc_metastore_federation.transports.DataprocMetastoreFederationGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DataprocMetastoreFederationClient( + 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", [ + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport, "grpc", grpc_helpers), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_dataproc_metastore_federation_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( + "metastore.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="metastore.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.ListFederationsRequest, + dict, +]) +def test_list_federations(request_type, transport: str = 'grpc'): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore_federation.ListFederationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_federations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.ListFederationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFederationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_federations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreFederationClient( + credentials=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_federations), + '__call__') as call: + client.list_federations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.ListFederationsRequest() + +@pytest.mark.asyncio +async def test_list_federations_async(transport: str = 'grpc_asyncio', request_type=metastore_federation.ListFederationsRequest): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore_federation.ListFederationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_federations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.ListFederationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFederationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_federations_async_from_dict(): + await test_list_federations_async(request_type=dict) + + +def test_list_federations_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.ListFederationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_federations), + '__call__') as call: + call.return_value = metastore_federation.ListFederationsResponse() + client.list_federations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federations_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.ListFederationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_federations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore_federation.ListFederationsResponse()) + await client.list_federations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federations_flattened(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_federations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore_federation.ListFederationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_federations( + 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_federations_flattened_error(): + client = DataprocMetastoreFederationClient( + credentials=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_federations( + metastore_federation.ListFederationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_federations_flattened_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_federations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore_federation.ListFederationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore_federation.ListFederationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_federations( + 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_federations_flattened_error_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_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_federations( + metastore_federation.ListFederationsRequest(), + parent='parent_value', + ) + + +def test_list_federations_pager(transport_name: str = "grpc"): + client = DataprocMetastoreFederationClient( + 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_federations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + next_page_token='abc', + ), + metastore_federation.ListFederationsResponse( + federations=[], + next_page_token='def', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + ], + next_page_token='ghi', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_federations(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore_federation.Federation) + for i in results) +def test_list_federations_pages(transport_name: str = "grpc"): + client = DataprocMetastoreFederationClient( + 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_federations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + next_page_token='abc', + ), + metastore_federation.ListFederationsResponse( + federations=[], + next_page_token='def', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + ], + next_page_token='ghi', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_federations(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_federations_async_pager(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_federations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + next_page_token='abc', + ), + metastore_federation.ListFederationsResponse( + federations=[], + next_page_token='def', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + ], + next_page_token='ghi', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_federations(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, metastore_federation.Federation) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_federations_async_pages(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_federations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + next_page_token='abc', + ), + metastore_federation.ListFederationsResponse( + federations=[], + next_page_token='def', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + ], + next_page_token='ghi', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_federations(request={})).pages: # pragma: no branch + 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", [ + metastore_federation.GetFederationRequest, + dict, +]) +def test_get_federation(request_type, transport: str = 'grpc'): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore_federation.Federation( + name='name_value', + version='version_value', + endpoint_uri='endpoint_uri_value', + state=metastore_federation.Federation.State.CREATING, + state_message='state_message_value', + uid='uid_value', + ) + response = client.get_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.GetFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore_federation.Federation) + assert response.name == 'name_value' + assert response.version == 'version_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.state == metastore_federation.Federation.State.CREATING + assert response.state_message == 'state_message_value' + assert response.uid == 'uid_value' + + +def test_get_federation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreFederationClient( + credentials=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_federation), + '__call__') as call: + client.get_federation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.GetFederationRequest() + +@pytest.mark.asyncio +async def test_get_federation_async(transport: str = 'grpc_asyncio', request_type=metastore_federation.GetFederationRequest): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(metastore_federation.Federation( + name='name_value', + version='version_value', + endpoint_uri='endpoint_uri_value', + state=metastore_federation.Federation.State.CREATING, + state_message='state_message_value', + uid='uid_value', + )) + response = await client.get_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.GetFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore_federation.Federation) + assert response.name == 'name_value' + assert response.version == 'version_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.state == metastore_federation.Federation.State.CREATING + assert response.state_message == 'state_message_value' + assert response.uid == 'uid_value' + + +@pytest.mark.asyncio +async def test_get_federation_async_from_dict(): + await test_get_federation_async(request_type=dict) + + +def test_get_federation_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.GetFederationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_federation), + '__call__') as call: + call.return_value = metastore_federation.Federation() + client.get_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federation_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.GetFederationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_federation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore_federation.Federation()) + await client.get_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federation_flattened(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore_federation.Federation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_federation( + 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_federation_flattened_error(): + client = DataprocMetastoreFederationClient( + credentials=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_federation( + metastore_federation.GetFederationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_federation_flattened_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = metastore_federation.Federation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(metastore_federation.Federation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_federation( + 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_federation_flattened_error_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_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_federation( + metastore_federation.GetFederationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.CreateFederationRequest, + dict, +]) +def test_create_federation(request_type, transport: str = 'grpc'): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.CreateFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_federation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreFederationClient( + credentials=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_federation), + '__call__') as call: + client.create_federation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.CreateFederationRequest() + +@pytest.mark.asyncio +async def test_create_federation_async(transport: str = 'grpc_asyncio', request_type=metastore_federation.CreateFederationRequest): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.CreateFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_federation_async_from_dict(): + await test_create_federation_async(request_type=dict) + + +def test_create_federation_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.CreateFederationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_federation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federation_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.CreateFederationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_federation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federation_flattened(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_federation( + parent='parent_value', + federation=metastore_federation.Federation(name='name_value'), + federation_id='federation_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].federation + mock_val = metastore_federation.Federation(name='name_value') + assert arg == mock_val + arg = args[0].federation_id + mock_val = 'federation_id_value' + assert arg == mock_val + + +def test_create_federation_flattened_error(): + client = DataprocMetastoreFederationClient( + credentials=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_federation( + metastore_federation.CreateFederationRequest(), + parent='parent_value', + federation=metastore_federation.Federation(name='name_value'), + federation_id='federation_id_value', + ) + +@pytest.mark.asyncio +async def test_create_federation_flattened_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_federation( + parent='parent_value', + federation=metastore_federation.Federation(name='name_value'), + federation_id='federation_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].federation + mock_val = metastore_federation.Federation(name='name_value') + assert arg == mock_val + arg = args[0].federation_id + mock_val = 'federation_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_federation_flattened_error_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_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_federation( + metastore_federation.CreateFederationRequest(), + parent='parent_value', + federation=metastore_federation.Federation(name='name_value'), + federation_id='federation_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.UpdateFederationRequest, + dict, +]) +def test_update_federation(request_type, transport: str = 'grpc'): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.UpdateFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_federation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreFederationClient( + credentials=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_federation), + '__call__') as call: + client.update_federation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.UpdateFederationRequest() + +@pytest.mark.asyncio +async def test_update_federation_async(transport: str = 'grpc_asyncio', request_type=metastore_federation.UpdateFederationRequest): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.UpdateFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_federation_async_from_dict(): + await test_update_federation_async(request_type=dict) + + +def test_update_federation_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.UpdateFederationRequest() + + request.federation.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_federation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'federation.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_federation_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.UpdateFederationRequest() + + request.federation.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_federation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'federation.name=name_value', + ) in kw['metadata'] + + +def test_update_federation_flattened(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_federation( + federation=metastore_federation.Federation(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].federation + mock_val = metastore_federation.Federation(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_federation_flattened_error(): + client = DataprocMetastoreFederationClient( + credentials=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_federation( + metastore_federation.UpdateFederationRequest(), + federation=metastore_federation.Federation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_federation_flattened_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_federation( + federation=metastore_federation.Federation(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].federation + mock_val = metastore_federation.Federation(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_federation_flattened_error_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_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_federation( + metastore_federation.UpdateFederationRequest(), + federation=metastore_federation.Federation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.DeleteFederationRequest, + dict, +]) +def test_delete_federation(request_type, transport: str = 'grpc'): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.DeleteFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_federation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataprocMetastoreFederationClient( + credentials=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_federation), + '__call__') as call: + client.delete_federation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.DeleteFederationRequest() + +@pytest.mark.asyncio +async def test_delete_federation_async(transport: str = 'grpc_asyncio', request_type=metastore_federation.DeleteFederationRequest): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == metastore_federation.DeleteFederationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_federation_async_from_dict(): + await test_delete_federation_async(request_type=dict) + + +def test_delete_federation_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.DeleteFederationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_federation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federation_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = metastore_federation.DeleteFederationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_federation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_federation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_federation_flattened(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_federation( + 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_federation_flattened_error(): + client = DataprocMetastoreFederationClient( + credentials=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_federation( + metastore_federation.DeleteFederationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_federation_flattened_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_federation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_federation( + 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_federation_flattened_error_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_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_federation( + metastore_federation.DeleteFederationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.ListFederationsRequest, + dict, +]) +def test_list_federations_rest(request_type): + client = DataprocMetastoreFederationClient( + 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 = metastore_federation.ListFederationsResponse( + 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 = metastore_federation.ListFederationsResponse.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_federations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFederationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_federations_rest_required_fields(request_type=metastore_federation.ListFederationsRequest): + transport_class = transports.DataprocMetastoreFederationRestTransport + + 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_federations._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_federations._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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore_federation.ListFederationsResponse() + # 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 = metastore_federation.ListFederationsResponse.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_federations(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_federations_rest_unset_required_fields(): + transport = transports.DataprocMetastoreFederationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_federations._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_federations_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreFederationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreFederationRestInterceptor(), + ) + client = DataprocMetastoreFederationClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "post_list_federations") as post, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "pre_list_federations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore_federation.ListFederationsRequest.pb(metastore_federation.ListFederationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore_federation.ListFederationsResponse.to_json(metastore_federation.ListFederationsResponse()) + + request = metastore_federation.ListFederationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore_federation.ListFederationsResponse() + + client.list_federations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_federations_rest_bad_request(transport: str = 'rest', request_type=metastore_federation.ListFederationsRequest): + client = DataprocMetastoreFederationClient( + 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_federations(request) + + +def test_list_federations_rest_flattened(): + client = DataprocMetastoreFederationClient( + 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 = metastore_federation.ListFederationsResponse() + + # 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 = metastore_federation.ListFederationsResponse.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_federations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*}/federations" % client.transport._host, args[1]) + + +def test_list_federations_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreFederationClient( + 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_federations( + metastore_federation.ListFederationsRequest(), + parent='parent_value', + ) + + +def test_list_federations_rest_pager(transport: str = 'rest'): + client = DataprocMetastoreFederationClient( + 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 = ( + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + next_page_token='abc', + ), + metastore_federation.ListFederationsResponse( + federations=[], + next_page_token='def', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + ], + next_page_token='ghi', + ), + metastore_federation.ListFederationsResponse( + federations=[ + metastore_federation.Federation(), + metastore_federation.Federation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(metastore_federation.ListFederationsResponse.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_federations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, metastore_federation.Federation) + for i in results) + + pages = list(client.list_federations(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", [ + metastore_federation.GetFederationRequest, + dict, +]) +def test_get_federation_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/federations/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 = metastore_federation.Federation( + name='name_value', + version='version_value', + endpoint_uri='endpoint_uri_value', + state=metastore_federation.Federation.State.CREATING, + state_message='state_message_value', + uid='uid_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = metastore_federation.Federation.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_federation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, metastore_federation.Federation) + assert response.name == 'name_value' + assert response.version == 'version_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.state == metastore_federation.Federation.State.CREATING + assert response.state_message == 'state_message_value' + assert response.uid == 'uid_value' + + +def test_get_federation_rest_required_fields(request_type=metastore_federation.GetFederationRequest): + transport_class = transports.DataprocMetastoreFederationRestTransport + + 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_federation._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_federation._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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = metastore_federation.Federation() + # 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 = metastore_federation.Federation.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_federation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_federation_rest_unset_required_fields(): + transport = transports.DataprocMetastoreFederationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_federation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_federation_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreFederationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreFederationRestInterceptor(), + ) + client = DataprocMetastoreFederationClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "post_get_federation") as post, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "pre_get_federation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore_federation.GetFederationRequest.pb(metastore_federation.GetFederationRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = metastore_federation.Federation.to_json(metastore_federation.Federation()) + + request = metastore_federation.GetFederationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = metastore_federation.Federation() + + client.get_federation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_federation_rest_bad_request(transport: str = 'rest', request_type=metastore_federation.GetFederationRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/federations/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_federation(request) + + +def test_get_federation_rest_flattened(): + client = DataprocMetastoreFederationClient( + 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 = metastore_federation.Federation() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/federations/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 = metastore_federation.Federation.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_federation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/federations/*}" % client.transport._host, args[1]) + + +def test_get_federation_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreFederationClient( + 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_federation( + metastore_federation.GetFederationRequest(), + name='name_value', + ) + + +def test_get_federation_rest_error(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.CreateFederationRequest, + dict, +]) +def test_create_federation_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["federation"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'version': 'version_value', 'backend_metastores': {}, 'endpoint_uri': 'endpoint_uri_value', 'state': 1, 'state_message': 'state_message_value', 'uid': 'uid_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 = operations_pb2.Operation(name='operations/spam') + + # 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.create_federation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_federation_rest_required_fields(request_type=metastore_federation.CreateFederationRequest): + transport_class = transports.DataprocMetastoreFederationRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["federation_id"] = "" + 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 + assert "federationId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_federation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "federationId" in jsonified_request + assert jsonified_request["federationId"] == request_init["federation_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["federationId"] = 'federation_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_federation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("federation_id", "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' + assert "federationId" in jsonified_request + assert jsonified_request["federationId"] == 'federation_id_value' + + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_federation(request) + + expected_params = [ + ( + "federationId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_federation_rest_unset_required_fields(): + transport = transports.DataprocMetastoreFederationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_federation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("federationId", "requestId", )) & set(("parent", "federationId", "federation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_federation_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreFederationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreFederationRestInterceptor(), + ) + client = DataprocMetastoreFederationClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "post_create_federation") as post, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "pre_create_federation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore_federation.CreateFederationRequest.pb(metastore_federation.CreateFederationRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore_federation.CreateFederationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_federation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_federation_rest_bad_request(transport: str = 'rest', request_type=metastore_federation.CreateFederationRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["federation"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'version': 'version_value', 'backend_metastores': {}, 'endpoint_uri': 'endpoint_uri_value', 'state': 1, 'state_message': 'state_message_value', 'uid': 'uid_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_federation(request) + + +def test_create_federation_rest_flattened(): + client = DataprocMetastoreFederationClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # 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', + federation=metastore_federation.Federation(name='name_value'), + federation_id='federation_id_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_federation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*}/federations" % client.transport._host, args[1]) + + +def test_create_federation_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreFederationClient( + 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_federation( + metastore_federation.CreateFederationRequest(), + parent='parent_value', + federation=metastore_federation.Federation(name='name_value'), + federation_id='federation_id_value', + ) + + +def test_create_federation_rest_error(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.UpdateFederationRequest, + dict, +]) +def test_update_federation_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'federation': {'name': 'projects/sample1/locations/sample2/federations/sample3'}} + request_init["federation"] = {'name': 'projects/sample1/locations/sample2/federations/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'version': 'version_value', 'backend_metastores': {}, 'endpoint_uri': 'endpoint_uri_value', 'state': 1, 'state_message': 'state_message_value', 'uid': 'uid_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 = operations_pb2.Operation(name='operations/spam') + + # 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.update_federation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_federation_rest_required_fields(request_type=metastore_federation.UpdateFederationRequest): + transport_class = transports.DataprocMetastoreFederationRestTransport + + 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_federation._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_federation._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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_federation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_federation_rest_unset_required_fields(): + transport = transports.DataprocMetastoreFederationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_federation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "federation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_federation_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreFederationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreFederationRestInterceptor(), + ) + client = DataprocMetastoreFederationClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "post_update_federation") as post, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "pre_update_federation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore_federation.UpdateFederationRequest.pb(metastore_federation.UpdateFederationRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore_federation.UpdateFederationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_federation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_federation_rest_bad_request(transport: str = 'rest', request_type=metastore_federation.UpdateFederationRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'federation': {'name': 'projects/sample1/locations/sample2/federations/sample3'}} + request_init["federation"] = {'name': 'projects/sample1/locations/sample2/federations/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'version': 'version_value', 'backend_metastores': {}, 'endpoint_uri': 'endpoint_uri_value', 'state': 1, 'state_message': 'state_message_value', 'uid': 'uid_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_federation(request) + + +def test_update_federation_rest_flattened(): + client = DataprocMetastoreFederationClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'federation': {'name': 'projects/sample1/locations/sample2/federations/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + federation=metastore_federation.Federation(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_federation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{federation.name=projects/*/locations/*/federations/*}" % client.transport._host, args[1]) + + +def test_update_federation_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreFederationClient( + 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_federation( + metastore_federation.UpdateFederationRequest(), + federation=metastore_federation.Federation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_federation_rest_error(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + metastore_federation.DeleteFederationRequest, + dict, +]) +def test_delete_federation_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/federations/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(name='operations/spam') + + # 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.delete_federation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_federation_rest_required_fields(request_type=metastore_federation.DeleteFederationRequest): + transport_class = transports.DataprocMetastoreFederationRestTransport + + 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_federation._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_federation._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 "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # 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 = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_federation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_federation_rest_unset_required_fields(): + transport = transports.DataprocMetastoreFederationRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_federation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_federation_rest_interceptors(null_interceptor): + transport = transports.DataprocMetastoreFederationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataprocMetastoreFederationRestInterceptor(), + ) + client = DataprocMetastoreFederationClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "post_delete_federation") as post, \ + mock.patch.object(transports.DataprocMetastoreFederationRestInterceptor, "pre_delete_federation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = metastore_federation.DeleteFederationRequest.pb(metastore_federation.DeleteFederationRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = metastore_federation.DeleteFederationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_federation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_federation_rest_bad_request(transport: str = 'rest', request_type=metastore_federation.DeleteFederationRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/federations/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_federation(request) + + +def test_delete_federation_rest_flattened(): + client = DataprocMetastoreFederationClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/federations/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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_federation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/federations/*}" % client.transport._host, args[1]) + + +def test_delete_federation_rest_flattened_error(transport: str = 'rest'): + client = DataprocMetastoreFederationClient( + 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_federation( + metastore_federation.DeleteFederationRequest(), + name='name_value', + ) + + +def test_delete_federation_rest_error(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DataprocMetastoreFederationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DataprocMetastoreFederationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataprocMetastoreFederationClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DataprocMetastoreFederationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DataprocMetastoreFederationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataprocMetastoreFederationClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataprocMetastoreFederationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DataprocMetastoreFederationClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataprocMetastoreFederationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DataprocMetastoreFederationGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DataprocMetastoreFederationGrpcTransport, + transports.DataprocMetastoreFederationGrpcAsyncIOTransport, + transports.DataprocMetastoreFederationRestTransport, +]) +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 = DataprocMetastoreFederationClient.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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DataprocMetastoreFederationGrpcTransport, + ) + +def test_dataproc_metastore_federation_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DataprocMetastoreFederationTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_dataproc_metastore_federation_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.metastore_v1beta.services.dataproc_metastore_federation.transports.DataprocMetastoreFederationTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DataprocMetastoreFederationTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_federations', + 'get_federation', + 'create_federation', + 'update_federation', + 'delete_federation', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_dataproc_metastore_federation_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.metastore_v1beta.services.dataproc_metastore_federation.transports.DataprocMetastoreFederationTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataprocMetastoreFederationTransport( + 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_dataproc_metastore_federation_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.metastore_v1beta.services.dataproc_metastore_federation.transports.DataprocMetastoreFederationTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataprocMetastoreFederationTransport() + adc.assert_called_once() + + +def test_dataproc_metastore_federation_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) + DataprocMetastoreFederationClient() + 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.DataprocMetastoreFederationGrpcTransport, + transports.DataprocMetastoreFederationGrpcAsyncIOTransport, + ], +) +def test_dataproc_metastore_federation_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.DataprocMetastoreFederationGrpcTransport, + transports.DataprocMetastoreFederationGrpcAsyncIOTransport, + transports.DataprocMetastoreFederationRestTransport, + ], +) +def test_dataproc_metastore_federation_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.DataprocMetastoreFederationGrpcTransport, grpc_helpers), + (transports.DataprocMetastoreFederationGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_dataproc_metastore_federation_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( + "metastore.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="metastore.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DataprocMetastoreFederationGrpcTransport, transports.DataprocMetastoreFederationGrpcAsyncIOTransport]) +def test_dataproc_metastore_federation_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_dataproc_metastore_federation_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.DataprocMetastoreFederationRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_dataproc_metastore_federation_rest_lro_client(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_dataproc_metastore_federation_host_no_port(transport_name): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='metastore.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'metastore.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://metastore.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_dataproc_metastore_federation_host_with_port(transport_name): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='metastore.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'metastore.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://metastore.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_dataproc_metastore_federation_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DataprocMetastoreFederationClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DataprocMetastoreFederationClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_federations._session + session2 = client2.transport.list_federations._session + assert session1 != session2 + session1 = client1.transport.get_federation._session + session2 = client2.transport.get_federation._session + assert session1 != session2 + session1 = client1.transport.create_federation._session + session2 = client2.transport.create_federation._session + assert session1 != session2 + session1 = client1.transport.update_federation._session + session2 = client2.transport.update_federation._session + assert session1 != session2 + session1 = client1.transport.delete_federation._session + session2 = client2.transport.delete_federation._session + assert session1 != session2 +def test_dataproc_metastore_federation_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataprocMetastoreFederationGrpcTransport( + 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_dataproc_metastore_federation_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataprocMetastoreFederationGrpcAsyncIOTransport( + 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.DataprocMetastoreFederationGrpcTransport, transports.DataprocMetastoreFederationGrpcAsyncIOTransport]) +def test_dataproc_metastore_federation_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.DataprocMetastoreFederationGrpcTransport, transports.DataprocMetastoreFederationGrpcAsyncIOTransport]) +def test_dataproc_metastore_federation_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_dataproc_metastore_federation_grpc_lro_client(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_dataproc_metastore_federation_grpc_lro_async_client(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_federation_path(): + project = "squid" + location = "clam" + federation = "whelk" + expected = "projects/{project}/locations/{location}/federations/{federation}".format(project=project, location=location, federation=federation, ) + actual = DataprocMetastoreFederationClient.federation_path(project, location, federation) + assert expected == actual + + +def test_parse_federation_path(): + expected = { + "project": "octopus", + "location": "oyster", + "federation": "nudibranch", + } + path = DataprocMetastoreFederationClient.federation_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreFederationClient.parse_federation_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DataprocMetastoreFederationClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = DataprocMetastoreFederationClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreFederationClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = DataprocMetastoreFederationClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = DataprocMetastoreFederationClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreFederationClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DataprocMetastoreFederationClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = DataprocMetastoreFederationClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreFederationClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = DataprocMetastoreFederationClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = DataprocMetastoreFederationClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreFederationClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = DataprocMetastoreFederationClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = DataprocMetastoreFederationClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DataprocMetastoreFederationClient.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.DataprocMetastoreFederationTransport, '_prep_wrapped_messages') as prep: + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DataprocMetastoreFederationTransport, '_prep_wrapped_messages') as prep: + transport_class = DataprocMetastoreFederationClient.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 = DataprocMetastoreFederationAsyncClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/services/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_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/services/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 = policy_pb2.Policy() + + # 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_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/services/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.set_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/services/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 = policy_pb2.Policy() + + # 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.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/services/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.test_iam_permissions(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/services/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 = iam_policy_pb2.TestIamPermissionsResponse() + + # 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.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationAsyncClient( + 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_get_operation(transport: str = "grpc"): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationAsyncClient( + 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationAsyncClient( + 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationAsyncClient( + 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value 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 = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value 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 = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationAsyncClient( + 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_set_iam_policy(transport: str = "grpc"): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the 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, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = DataprocMetastoreFederationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = DataprocMetastoreFederationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DataprocMetastoreFederationClient( + 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 = DataprocMetastoreFederationClient( + 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", [ + (DataprocMetastoreFederationClient, transports.DataprocMetastoreFederationGrpcTransport), + (DataprocMetastoreFederationAsyncClient, transports.DataprocMetastoreFederationGrpcAsyncIOTransport), +]) +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, + )